Generating the Hex Digits of Pi
Seeing as it's Pi Day (3/14) I thought I'd post the little Python script I wrote at PyCon implementing Simon Plouffe's remarkable formula for pi in hex.
def pi():
N = 0
n, d = 0, 1
while True:
xn = (120*N**2 + 151*N + 47)
xd = (512*N**4 + 1024*N**3 + 712*N**2 + 194*N + 15)
n = ((16 * n * xd) + (xn * d)) % (d * xd)
d *= xd
yield 16 * n // d
N += 1
For example, the following code displays the first 2000 digits.
pi_gen = pi()
import sys
sys.stdout.write("pi = 3.")
for i in range(2000):
sys.stdout.write("0123456789ABCDEF"[pi_gen.next()])
sys.stdout.write("\n")
You'll notice that pi in hex begins 3.24 so perhaps I should have waited another 10 days :-)
And if you're wondering why the hex digit after the point is higher that the decimal equivalent, remember that after the point, hex digits are worth less than their decimal equivalents.
Comments (5)
James Tauber on March 14, 2007:
Charles McCreary on March 15, 2007:
pi_gen.next()
generates an index into the string of hex digits, but I've never seen that syntax before. Any particular place where that might be documented?
Charles McCreary on March 15, 2007:
a_string = "abcdefghi"
a_string[5] = f
"abcdefghi"[5] = f
Do me a favor ... delete my previous stupid comment.
Cliff on May 23, 2008:
$ python pihex.py 16
to get 16 hex digits of pi. I tried running pihex.py 65536 and found that after a while the program seemed to hang for several minutes, and then print out a half page of digits. In order to make it more palatable, I added a sys.stdout.flush() after sys.stdout.write("0123456789ABCDEF"[pi_gen.next()]). That way each digit prints out on its own. It's easier to follow what's going on. My full code is here: http://dpaste.com/hold/52337/
Thanks for this great link
Add a Comment
Last Modified: March 14, 2007
Author: jtauber
Nadav Samet on March 14, 2007:
In Israel we celebrate the Pi day approximately on 22/7, as we write the day-of-month before the month.