Why is this giving me a bad estimation of pi (Leibniz formula)

Question:

Leibniz formula is

π/4 = 1 – 1/3 + 1/5 – 1/7 + 1/9 – …

Or, π = 4 ( 1 – 1/3 + 1/5 – 1/7 + 1/9 – … )

I don’t really understand why my code is producing a bad result. There is another way of doing this, but what is wrong with my code specifically? It seems like it should give me a good result.

it = int(input("Enter number of iterations: "))

denom = 3
approx = 1
count = 0

while count < it:
    if count % 2 == 0: #count is even
        approx -= 1/denom

    elif count % 2 == 1: #count is odd
        approx +=  1/denom

    denom += 2
    count += 1

approx *= 4 #multiply by 4 gets the final result


print("The approximation of pi is ", approx)

#For 5, The approximation of pi should be 3.3396825396825403

My output is:

Enter number of iterations: 5
The approximation of pi is  2.9760461760461765

The expected output should be:

Enter number of iterations: 5
The approximation of pi should be 3.3396825396825403
Asked By: Spellbinder2050

||

Answers:

You’re off by one – the starting value 1 (for approx and denom) counts as an iteration. How about this:

denom = 1
approx = 0
count = 1

while count <= it:
    if count % 2 == 0: #count is even
        approx -= 1/denom
    elif count % 2 == 1: #count is odd
        approx +=  1/denom
    print(count, denom, approx*4)
    denom += 2
    count += 1

gives you

1 1 4.0
2 3 2.666666666666667
3 5 3.466666666666667
4 7 2.8952380952380956
5 9 3.3396825396825403
6 11 2.9760461760461765
7 13 3.2837384837384844
8 15 3.017071817071818
9 17 3.2523659347188767
10 19 3.0418396189294032
11 21 3.232315809405594
12 23 3.058402765927333
13 25 3.2184027659273333
14 27 3.0702546177791854
15 29 3.208185652261944
16 31 3.079153394197428
17 33 3.200365515409549
18 35 3.0860798011238346
19 37 3.1941879092319425
20 39 3.09162380666784
Answered By: Tim Pietzcker
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.