[Tutor] How to calculate pi with another formula?

Dick Moores rdm at rcblue.com
Sun Oct 31 11:05:09 CET 2004


Thanks, Gregor! I downloaded just the decimal module (thanks to Kent), 
and found the doc for decimal, 
<http://www.python.org/dev/doc/devel/lib/module-decimal.html>.

Exciting!

Thanks,

Dick

At 10:27 10/29/2004, Gregor Lingl wrote:
>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
>
>
>Dick Moores schrieb:
>
>>Is it possible to calculate almost-pi/2 using the (24) formula on 
>><http://mathworld.wolfram.com/PiFormulas.html> without using (23)?
>>
>>If it's possible, how about a hint? Recursion?
>>
>>Thanks, tutors.
>>
>>Dick Moores
>>rdm at rcblue.com




More information about the Tutor mailing list