Use a for
loop to estimate $\pi$ from the first 20 terms of the Madhava series:
$$
\pi = \sqrt{12} \left( 1 - \frac{1}{3\cdot 3} + \frac{1}{5\cdot 3^2} - \frac{1}{7\cdot 3^3} + \cdots \right).
$$
The following calculates $\pi$ to 10 decimal places.
>>> import math
>>> pi = 0
>>> for k in range(20):
... pi += pow(-3, -k) / (2*k+1)
...
>>> pi *= math.sqrt(12)
>>> print('pi = ', pi)
pi = 3.1415926535714034
>>> print('error = ', abs(pi - math.pi))
error = 1.8389734179891093e-11
Note that the built-in pow(x, j)
is equivalent to (x)**j
.