James Tauber

journeyman of some

blog > 2007 > 03 > 14 >

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.

Categories:
prev « python » next
prev « mathematics » next

Comments (5)

Nadav Samet on March 14, 2007:

Hi James,

In Israel we celebrate the Pi day approximately on 22/7, as we write the day-of-month before the month.

James Tauber on March 14, 2007:

LOL, Nadav.

Charles McCreary on March 15, 2007:

I feel stupid for asking, but that's never slowed me down before. It's clear that
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:

Doh!!!
a_string = "abcdefghi"
a_string[5] = f
"abcdefghi"[5] = f
Do me a favor ... delete my previous stupid comment.

Cliff on May 23, 2008:

I modified the script by putting the runner in an if __name__ == '__main__' block, and changing 2000 to sys.argv[1]. So you could run it as

$ 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

Created: March 14, 2007
Last Modified: March 14, 2007
Author: jtauber