[Tutor] How to calculate pi with another formula?

Dick Moores rdm at rcblue.com
Tue Apr 12 14:05:53 CEST 2005


Gregor Lingl wrote at 11:27 10/29/2004:
>Hi Dick!
>
>Accidentally I just was tinkering around with the new
>decimal module of Python2.4. (By the way: it also works
>with Python 2.3 - just copy it into /Python23/Lib)
>
>The attached program uses a very elementary (and inefficient)
>formula to calculate pi, namely as the area of a 6*2**n-sided
>polygon (starting with n=0), inscribed into a circle of radius 1.
>(Going back to Archimedes, if I'm right ...)
>
>Nevertheless it calculates pi with a precision of (nearly)
>100 digits, and the precision can be  arbitrarily enlarged.
>In the output of this program only the last digit is not correct.
>
>import decimal
>
>decimal.getcontext().prec = 100
>
>def calcpi():
>    s = decimal.Decimal(1)
>    h = decimal.Decimal(3).sqrt()/2
>    n = 6
>    for i in range(170):
>        A = n*h*s/2  # A ... area of polygon
>        print i,":",A
>        s2 = ((1-h)**2+s**2/4)
>        s = s2.sqrt()
>        h = (1-s2/4).sqrt()
>        n = 2*n
>
>calcpi()
>
>Just for fun ...
>
>Gregor

This works great, and if I change the precision to, say, 2000, and the 
range to 2000, I get pi accurate to the 1,205th digit (this took 66 
minutes, with psyco employed), when I compare with the pi pages on the web.

Now to my new question. I have an artist friend who knows an artist who 
needs pi expressed in base 12. I don't know how many digits he needs, but 
I think he'll take what he can get. Is there a way to use math.log(x, 
base) with the decimal module to accomplish this? Or is there another 
way? Or is there no way?

Thanks,

Dick Moores
rdm at rcblue.com



More information about the Tutor mailing list