based off my previous challenge, this wikipedia article, and a Scratch project
Your task: given i
, calculate \$\pi\$ till i
terms of the Gregory-Leibniz series.
The series:
$$\pi=\frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\frac{4}{9}-...$$
Here, 4/1
is the first term, -4/3
is the second, 4/5
is the second and so on.
Note that for the nth term,
- $$\text S_n = \frac{4 \times (-1)^{n+1}}{2n-1}$$
- $$\pi_n = \text S_1 + \text S_2 + ... + \text S_n,$$ where \$\pi_n\$ is \$\pi\$ approximated to \$n\$ terms.
Test cases:
In - Out
1 - 4
2 - 2.66666667
3 - 3.46666667
4 - 2.8952381
Floating point issues are OK.
You may not calculate infinite terms of pi using this as we are calculating a number rather than terms of a series here.
This is code-golf, so shortest answer wins!
EDIT: It's strange that this question got some new... activity.