More fun with GMP

January 14, 2004

Here’s yet another neat little toy using python and the Gnu Multiprecision library bindings. It calculates Pi using Ramanujan’s series for 1/Pi:

def rama(nsteps,prec=10):
    from gmpy import mpf
    pre = mpf('8',prec).sqrt()/mpf('9801',prec)
    sum = mpf('0',prec)
    for i in range(nsteps):
        num = fact(4*i)*(1103+26390*i)
        den = pow(fact(i),4)*pow(396,4*i)
        sum += mpf(num,prec)/mpf(den,prec)
    print mpf(1,prec)/(pre*sum)

It’s not as pretty as the pure python version:

def rama(nsteps):
    pre = sqrt(8)/9101.
    sum = 0
    for i in range(nsteps): sum += fact(4,i)*(1103+26390*i)/pow(fact(i),4)/pow(396,4*i)
    print 1./pre/sum

But it’s cool to have high precision calculations for so little effort.

The page here has a neat implementation of this algorithm in Javascript, where they explicitly do the high-precision math using JS arrays. Sweet.

And as long as we’re talking about pi, the ProjectPi group at Sourceforge has released a lot of cute implementations for computing pi.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: