954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Approximation of Pi (Python)

0
By vegaseat on Mar 27th, 2006 1:04 am

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
"""

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

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

Do you have a link for this particular algorithm?

Thanks,
Jeff

jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156
 

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!

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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.

kogorman
Newbie Poster
6 posts since Jul 2007
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You