[Edu-sig] one solution (OST pi day challenge)

Kirby Urner kurner at oreillyschool.com
Mon Mar 14 23:16:41 CET 2011


"""
"make math your own, to make your own math"
   -- Maria Droujkova

See:
http://mail.python.org/pipermail/edu-sig/2011-March/010224.html
http://worldgame.blogspot.com/2011/03/pycon-2011.html
http://groups.google.com/group/mathfuture/msg/4a847eb3cc12db77?hl=en
"""

def makepi():
    """Pi to a thousand places

    Ramanujan's freakish formula
    http://worldgame.blogspot.com/2008/02/reflective-fragment.html
    """
    # using_gmpy()
    thegen = ramanujan(4000)
    while True:
        term1 = next(thegen)
        term2 = next(thegen)
        if term1 == term2:  # just lucky?
            break
    return str(term2)[:1001]

# http://code.google.com/p/gmpy/
import gmpy  # pre-installed binary gmpy2-2.0.0a1.win32-py3.1.exe


def ramanujan(p=1000):
    gmpy.set_minprec(p)
    term = gmpy.fsqrt(gmpy.mpf(8))/gmpy.mpz(9801)
    n = gmpy.mpz(0)
    thesum = gmpy.mpz(0)
    while True:
        numer = (gmpy.fac(4*n)*(gmpy.mpz(1103) + gmpy.mpz(26390)*n))
        denom = (gmpy.fac(n)**4)*(gmpy.mpz(396)**(4*n))
        theterm = numer/denom
        thesum += theterm
        ans = term * thesum
        yield 1/ans
        n += 1

if __name__ == "__main__":
    print (makepi())


More information about the Edu-sig mailing list