pythonpi

Python Pi approximation


So I have to approximate Pi with following way: 4*(1-1/3+1/5-1/7+1/9-...). Also it should be based on number of iterations. So the function should look like this:

>>> piApprox(1)
4.0
>>> piApprox(10)
3.04183961893
>>> piApprox(300)
3.13825932952

But it works like this:

>>> piApprox(1)
4.0
>>> piApprox(10)
2.8571428571428577
>>> piApprox(300)
2.673322240709928

What am I doing wrong? Here is the code:

def piApprox(num):
    pi=4.0
    k=1.0
    est=1.0
    while 1<num:
        k+=2
        est=est-(1/k)+1/(k+2)
        num=num-1

    return pi*est

Solution

  • This is what you're computing:

    4*(1-1/3+1/5-1/5+1/7-1/7+1/9...)
    

    You can fix it just by adding a k += 2 at the end of your loop:

    def piApprox(num):
        pi=4.0
        k=1.0
        est=1.0
        while 1<num:
            k+=2
            est=est-(1/k)+1/(k+2)
            num=num-1
            k+=2
        return pi*est
    

    Also the way you're counting your iterations is wrong since you're adding two elements at the time.

    This is a cleaner version that returns the output that you expect for 10 and 300 iterations:

    def approximate_pi(rank):
        value = 0
        for k in xrange(1, 2*rank+1, 2):
            sign = -(k % 4 - 2)
            value += float(sign) / k
        return 4 * value
    

    Here is the same code but more compact:

    def approximate_pi(rank):
        return 4 * sum(-float(k%4 - 2) / k for k in xrange(1, 2*rank+1, 2))