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):

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.

The original post was in the categories: python mathematics but I'm still in the process of migrating categories over.

The original post had 5 comments I'm in the process of migrating over.