-1

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)
Tagc
  • 8,736
  • 7
  • 61
  • 114
Daniel Nicholson
  • 41
  • 1
  • 1
  • 7

2 Answers2

5

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.

wim
  • 338,267
  • 99
  • 616
  • 750
2

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
Community
  • 1
  • 1
Tagc
  • 8,736
  • 7
  • 61
  • 114
  • You may assume Python 3, because otherwise the division `1/t` would have returned 0 and the original code could not have produced 0.1963.. – wim Jan 09 '17 at 18:23
  • That is not a very good approximation for pi. Two accurate digits hardly seems worth the effort. – duffymo Jan 09 '17 at 18:40
  • @duffymo It was just an example to demonstrate. What I have demonstrates the point fine, and all that's required to get a more accurate estimate is to increase the argument passed to `estimate_pi`. – Tagc Jan 09 '17 at 18:41
  • Just checked the convergence of the Leibniz formula: https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80. Sub-linear convergence explains it. I expected something like Taylor series for sine and cosine, which both exhibit quadratic convergence. I feared that the low accuracy reflected on your solution, but that does not appear to be the case. – duffymo Jan 09 '17 at 18:45
  • @duffymo Yeah that makes sense. I have to bump the number up quite high to get anything much more accurate. – Tagc Jan 09 '17 at 18:48