Leibniz_Pi.py
Cousin Stanley
CousinStanley at HotMail.com
Fri Oct 11 13:14:38 EDT 2002
Yesterday in the news group comp.lang.java.help
I found a Java example of the Leibniz Pi approximation
and converted the Java code to Python ...
The numerical results from either version
using a LARGE number of terms as a program argument
provide approximations for the number Pi that seems correct ...
Using 1 million terms as an input argument,
the Java version is a bit faster, which I think
is expected ...
On a 250 MHz Win98 machine ...
Java SDK 1.4 ....... ~ 3-4 seconds
Python 2.2.1 ......... ~ 9-10 seconds
Since I am fairly new to BOTH Java AND Python,
I'm wondering if there are any ...
obvious oversights ???
Python improvements ???
Python code follows ...
Cousin Stanley
----------------------------------------------------------------
'''
Leibniz_Pi.py
Pi = 4 * ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 ... )
Using one million terms provides a good approximation ...
Posted to the NewsGroup
comp.lang.java.help 2002-10-10
By Jonas Lindström
Converted to Python
By Stanley C. Kitching
'''
import sys
print '\n Approximate Pi via Leibniz Sequence '
def calculate_pi( nTerms ) :
limit = ( 2 * nTerms ) - 1
if ( ( limit - 1 ) % 4 ) == 0 :
sign = +1.0
else :
sign = -1.0
sum = 0.0
for i in range( limit , 0 , -2 ) :
sum += sign / i
sign = -sign
return 4.0 * sum
nTerms = int( sys.argv[ 1 ] )
Pi = calculate_pi( nTerms )
print '\n Terms : ' , nTerms
print '\n Pi : ' , Pi
More information about the Python-list
mailing list