Posts Tagged ‘sympy’

Digits of PI (Part 2)

April 13, 2012 Leave a comment

On the Python mailing list I got some great answers on how to generate the digits of PI. Here I sum them up.

Solution 1
Tichodroma forwarded me to


Here's a generator I coded up based on a paper by Gibbons:

It's simple to code, but I think you have to read the paper to figure out what 
it's doing. (I just translated some code, so I really can't tell you :-) In 
the paper, this was done in a lazy functional language. I was mostly 
interested to see how it would translate to a Python generator.

# -- imlementation of Gibbons' spigot algorithm for pi
#  John Zelle 4-5-06

def pi_digits():
    """generator for digits of pi"""
    q,r,t,k,n,l = 1,0,1,1,3,3
    while True:
        if 4*q+r-t < n*t:
            yield n
            q,r,t,k,n,l = (10*q,10*(r-n*t),t,k,(10*(3*q+r))/t-10*n,l)
            q,r,t,k,n,l = (q*k,(2*q+r)*l,t*l,k+1,(q*(7*k+2)+r*l)/(t*l),l+2)

Here it is in action:

>>> import pi
>>> digits = pi.pidigits()
>>> for i in range(30): print,
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7

Since this uses long ints, it slows down considerably after a few thousand 
digits. You might want to use psyco when generating really "deep" digits.


It generates the digits of PI one after the other. It works well bit if you want lots of digits, it gets really slow.

Solution 2
E. Woiski suggested using the library SymPy.

sudo apt-get install python-sympy
>>> from sympy.mpmath import mp
>>> mp.dps = 1000   # number of digits
>>> +mp.pi    # str(mp.pi)

Very fast and simple. The only problem might be that you need to install sympy.

Solution 3 (update, 20121128)
One of my students called G. Szegedi came up with this solution:

from bigfloat import precision
import bigfloat

str_pi = str(bigfloat.atan2(+0.0,-0.0,precision(1000)))

With the bigfloat package you can do high precision floating-point arithmetic.