Szczepenson
Szczepenson

Reputation: 55

Calculating pi in python - Leibnitz

I am starting my adventure with Python. My current program is very simple, it has to calculate pi using Leibnitz formula, and stop working when module from "a" varibale is less than x. So far, it looks like this:

from math import fabs
from math import pi

x=float(input('Enter accuracy of calculating:'))
sum=0
a=0
n=0

while True:
    a=float(((-1)**n)/(2*n+1))
    sum+=a
    n+=1
    result=sum*4

    if fabs(a)<x:
        break

print('Calculated pi:',result)
print('Imported pi:', pi)

It looks ok, but here's the problem: In my version of Geanie it works great, but on my friend's Geanie - it calculates 0.0. Also, on Ideone.com (without keyboard input, just e.g. x=0.0001) it also returns 0.0.

Does anyone knows where the problem is?

Upvotes: 1

Views: 641

Answers (1)

abcd
abcd

Reputation: 10761

Try this

a=((-1)**n)/float(2*n+1)

instead of this

a=float(((-1)**n)/(2*n+1))

Reason: I don't see a point to setting a itself to be a float, but setting the divisor or dividend in the division that produces a will ensure that Python doesn't cut the remainder (which is the default for integer division before Python 3.0).

Side issue: Your style doesn't match the official Python style guidelines, so you might want to change that.

Upvotes: 3

Related Questions