I’ve been trying to convert this math formula into python.
So basically the approximation of 1/math.pi.
I tried making this iteration with
import math N = 132 for k in range(1, N+1): print("The N value is",N , end="r", flush=True) rec_pi_approximate = (2*math.sqrt(2)/9801) * N * ((math.factorial(4*k) * (1103+26390*k))/((math.factorial(k)**4) * (396**4*k)))
But my values have been weird and I need guidance on how to actually type the formula and make a summation loop for it. Currently I am trying to find the reciprocal of pi with this formula equivalent to 1/math.pi
The idea with the
for loop is that you add up a part of the summation on each iteration. So you should keep track of the total sum so far and add to it each time. Because of math properties, you can multiply by the constant that’s outside the summation while summing so you don’t need to at the end.
import math N = 132 pi_approximate_inv = 0 for k in range(0, N+1): print("The N value is", k) pi_approximate_inv += (2*math.sqrt(2)/9801) * ((math.factorial(4*k) * (1103+26390*k))/((math.factorial(k)**4) * (396**(4*k)))) print("The pi approximate is", 1.0/pi_approximate_inv)
You also missed some parentheses at
(396**(4*k)) which I added. Also, it should be
print("The N value is", k) (
N) because it is showing what the result would be if it stopped right there at
Because of floating point precision limits, it appears to max out at N=2 (meaning 3 iterations).