Search code examples
pythonmathpi

Calculating pi with Leibniz Formula


I am trying to calculate pi using the Leibniz formula. However, my code seems to always produce '0.19634952834936123' at the end, which is obviously not pi.

Code:

import math
x = 0
y = 0
for t in range(1,10000001):
    if t % 2 != 0:
        y += 1
        if y % 2 != 0:
            x += 1/t
        else:
            x -= 1/t
    else:
        pass
print(x/4)

Solution

  • This sum converges to π/4, not to 4π. Therefore, you want to use the result

    x * 4
    

    Not

    x / 4
    

    Other than that, your code is working OK.