Posts Tagged ‘digits of pi’

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.

Digits of PI (Part 1)

April 13, 2012 Leave a comment

You want to work with the digits of PI. Why? For instance you want a new job (screenshot here if it got removed since then).

I like simple solutions. So instead of generating the digits, I simply fetched the data from the web. This is a fast, efficient, and painless approach of the problem :) Visit, where you can download several data files.

For the lazy pigs
I made a script that downloads the data, parses them, and returns the digits as a string. Here it is.

Usage (get the first 30 digits of PI after the dot):

#!/usr/bin/env python

from jabbapylib.math import pi

def main():
    digits = pi.get_digits_of(pi.PI3)    # get 10^3 = 1000 digits
    print digits[:30]

if __name__ == "__main__":



jabbapylib is here

Categories: python Tags: ,