Calculating pi with Leibniz Formula

2.5k Views Asked by At

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)
2

There are 2 best solutions below

0
On BEST ANSWER

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.

5
On

My IDE took a while to run your code. Additionally, if you're running that code in Python 2 that range expression is going to use up a lot of memory. If you'd like, here's an alternate approach that lazily generates the Leibniz formula terms to estimate pi. Python's generator functions seem ideally suited to this sort of task.

def estimate_pi(num_terms):
    return 4 * sum(x for x in generate_leibniz_terms(num_terms))


def generate_leibniz_terms(num_terms):
    denominator = 1
    sign = 1

    for _ in range(num_terms):
        yield sign * (1 / denominator)
        sign = -sign
        denominator += 2


print(estimate_pi(100))

Output

3.1315929035585537