Python pi calculation?

For people who come here just to get a ready solution to get arbitrary precision of pi with Python (source with a couple of edits):

import decimal

def pi():
    """
    Compute Pi to the current precision.

    Examples
    --------
    >>> print(pi())
    3.141592653589793238462643383

    Notes
    -----
    Taken from https://docs.python.org/3/library/decimal.html#recipes
    """
    decimal.getcontext().prec += 2  # extra digits for intermediate steps
    three = decimal.Decimal(3)      # substitute "three=3.0" for regular floats
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n + na, na + 8
        d, da = d + da, da + 32
        t = (t * n) / d
        s += t
    decimal.getcontext().prec -= 2
    return +s               # unary plus applies the new precision

decimal.getcontext().prec = 1000
pi = pi()

It seems you are losing precision in this line:

pi = pi * Decimal(12)/Decimal(640320**(1.5))

Try using:

pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))

This happens because even though Python can handle arbitrary scale integers, it doesn't do so well with floats.

Bonus

A single line implementation using another algorithm (the BBP formula):

from decimal import Decimal, getcontext
getcontext().prec=100
print sum(1/Decimal(16)**k * 
          (Decimal(4)/(8*k+1) - 
           Decimal(2)/(8*k+4) - 
           Decimal(1)/(8*k+5) -
           Decimal(1)/(8*k+6)) for k in range(100))