Search code examples
pythonpi

Python script for Leibniz number row


I am trying to write simple script in Python 2.7 for calculating Pi. I am interested in Leibniz formula:

π = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) ...

So I consider "(4/1) - (4/3)" as X, and 1-3-5 as y, y+2, y+4....

I wrote this script:

def pi():
    p = 0.0
    y = 1.0
    x = 4.0/y - 4.0/(y+2.0)
    for i in range(10000):
        p = p + x
        y += 4.0
    print p

pi()

It isn't working as intended; could you explain why?


Solution

  • This one works:

    def pi():
        p = 0.0
        y = 3.0
        x = 4.0 - 4/y
        for i in range(5000):
            y += 2
            x = x + 4/y
            y += 2
            x = x - 4/y
            print x
    
    pi()