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.

### Like this:

Like Loading...

*Related*

This entry was posted on January 14, 2004 at 1:46 pm and is filed under Python.

## Leave a Reply