Approximation of Pi (Python)

vegaseat 0 Tallied Votes 3K Views Share

For those of you who are inquisitive, here is a little Python program to approximate the value of pi to 77 digits. You can easily go further, just change the value n in range(n+1).

# a generator to approximate pi to n decimals
# the result is a string
# tested with Python24

def pi_generate():
    """generator to approximate pi"""
    q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
    while True:
        if 4 * q + r - t < m * t:
            yield m
            q, r, t, k, m, x = (10*q, 10*(r-m*t), t, k, (10*(3*q+r))//t - 10*m, x)
        else:
            q, r, t, k, m, x = (q*k, (2*q+r)*x, t*x, k+1, (q*(7*k+2)+r*x)//(t*x), x+2)

n = 77
digits = pi_generate()

# build a list of characters, the leading 3 and n decimals
pi_list = []
for i in range(n+1):
    pi_list.append(str(digits.next()))

# insert the missing period at index 1 (after the 3)    
pi_list.insert(1, '.')

#print pi_list  # test

# convert the list of characters to a string
pi_str = "".join(pi_list)

print "pi approximated to %d decimals (below it is the official pi):" % n
print pi_str
# official pi value
pi_pub = "3.14159265358979323846264338327950288419716939937510582097494459230781640628620"
print pi_pub

"""
result -->
pi approximated to 77 decimals (below it is the official pi):
3.14159265358979323846264338327950288419716939937510582097494459230781640628620
3.14159265358979323846264338327950288419716939937510582097494459230781640628620
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Switched to a highly efficient generator function and added more comments.

jrcagle 77 Practically a Master Poster

Do you have a link for this particular algorithm?

Thanks,
Jeff

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Sorry Jeff, don't have a link. This is from one of the many series expansions that float around the net. I know it is accurate for at least 77 places. I did add a comparison with the published real pi to it.

In the mean time a happy '4*math.atan(1)' to you!

kogorman 0 Newbie Poster

Here's a link to something that looks like it might have been the original.

http://mail.python.org/pipermail/edu-sig/2006-July/006810.html

This page contains a link to a math paper (PDF) where the idea was developed.

sneekula 969 Nearly a Posting Maven

Reminds me a little bit of the algorithm that appears in the Python manual for the decimal module. Check the recipes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.