Your task: given a nonzero positive number i
, calculate pi using the Nilakantha series unto i
terms.
The Nilakantha series is as follows:
$$\text 3 + \frac{4}{2 \times 3 \times 4} - \frac{4}{4 \times 5\times 6}+\frac{4}{6 \times 7 \times 8} - ...$$
3 is the first term, 4/2*3*4
is the second, -4/4*5*6
is the third, and so on.
Notice that for the nth term:
- $$\text S_1 = 3$$
- $$\text S_n = \frac{4 \times (-1)^n}{2n \times (2n-1) \times (2n-2)}$$
- The approximation of pi by summing up these terms is $$\text S_1 +\text S_2\text + … +\text S_n$$
Test cases:
In = Out
1 = 3
2 = 3.16666666667
3 = 3.13333333333
4 = 3.1452381
Notice the pattern of the numbers approximating towards pi.
Floating point issues are OK.
This is code-golf so shortest answer wins!
EDIT: by default this is 1-indexed, but if you want 0-indexed no problem, just mention it. And even infinitely printing the approximations with no input is Okay.
EDIT 2: Why some activity here?
i
by 0-based (e.g.0=3, 1=3.166..., 2=3.133..., 3=3.145...
)? Also, is there a reason for overwriting the default sequence rules? Or is outputting an infinite list of all items also allowed, without taking an input? \$\endgroup\$\times
instead of*
in mathjax \$\endgroup\$