which pi formula is given in the decimal module documentation?

Mark Dickinson dickinsm at gmail.com
Fri Dec 11 07:49:19 EST 2009


On Dec 11, 8:16 am, Anh Hai Trinh <anh.hai.tr... at gmail.com> wrote:
> I'm just curious which formula for pi is given here: <http://
> docs.python.org/library/decimal.html#recipes>?
>
> def pi():
>     """Compute Pi to the current precision.
>
>     >>> print pi()
>     3.141592653589793238462643383
>
>     """
>     getcontext().prec += 2  # extra digits for intermediate steps
>     three = 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
>     getcontext().prec -= 2
>     return +s               # unary plus applies the new precision

And just for fun, here's a one-liner (well, okay, two lines including
the import) that uses Decimal to print the first 28 digits of pi:

Python 2.6.4 (r264:75706, Nov 16 2009, 15:42:08)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from decimal import Decimal as D
>>> print reduce(lambda x,k:2+k/2*x/k,range(999,1,-2),D())
3.141592653589793238462643383

--
Mark



More information about the Python-list mailing list