[Tutor] How to calculate pi with another formula?

Barry Sperling barry at angleinc.com
Fri Oct 29 21:37:16 CEST 2004


Thanks, Gregor!
	As a newby I didn't know about such improvements, so I did what you 
suggested and added decimal.py to my lib directory in 2.3 and it worked. 
  Below is the code for the iterative answer ( different from the 
recursive one that Bill Mill gave ) that I suggested to Dick, originally 
as a text hint, but now using the decimal module:

import decimal

decimal.getcontext().prec = 40   # ARBITRARY UPPER LIMIT TO PRECISION

# ITERATIVE METHOD, USING THE NUMERATOR AS A COMPARISON
numer = decimal.Decimal(100)  # ARBITRARY UPPER LIMIT TO NUMERATOR
subtotal = decimal.Decimal(1)   # INITIALIZE
Last_Numerator = decimal.Decimal(1)   # COUNTING DOWN WE'LL STOP AT 1
Subtraction_Amount = decimal.Decimal(1)  # COUNTING DOWN BY 1s
Pi_Correction = decimal.Decimal(2)   # SINCE THE PRIOR CALC GIVES PI/2

while numer >= Last_Numerator:
   denom = 2 * numer + 1 #THE FORMULA DERIVING EACH DENOM FROM EACH NUMER
   subtotal = 1 + numer / denom * subtotal
   numer -= Subtraction_Amount   # WORKING FROM INSIDE-OUT

print Pi_Correction * subtotal

Barry


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)

 > 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)?
 >>
 >> Dick Moores
 >> rdm at rcblue.com


More information about the Tutor mailing list