Leibniz_Pi.py

Berthold Höllmann bhoel at web.de
Fri Oct 11 15:15:47 EDT 2002


"Cousin Stanley" <CousinStanley at HotMail.com> writes:

> 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 ???

Try Numeric for improvements:

On my PentiumII 350MHz, GNU/Linux, Kernel 2.4.18, SuSE 8.0
(calculate_pi2 is Numeric):

Approximate  Pi  via Leibniz Sequence 
calculate_pi1:  4.35253095627 s
calculate_pi2:  1.28464400768 s
Terms :  1000000
   Pi1:  3.14159165359
   Pi2:  3.14159165359
   Pi :  3.14159265359

My modified program follows.

Greetings
Berthold

''' 
    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
    Converted to Numeric
    By Berthold Höllmann
'''

import sys
import time
print 'Approximate  Pi  via Leibniz Sequence '

def calculate_pi1( 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 

def calculate_pi2( nTerms ) :
    import Numeric as N
    nn = (int(nTerms)+1)/2
    sign = N.ones((nn,2))*4
    sign[:,1] *= -1
    sign.shape = (-1,)
    div = N.arange(1,( 2 * nTerms ), 2, N.Float)
    return N.sum(sign[:nTerms]/div)


import math
nTerms = int(sys.argv[1]) 

import time
start = time.time()
Pi1 = calculate_pi1(nTerms)
Pi2 = calculate_pi2(nTerms)

start = time.time()
Pi1 = calculate_pi1(nTerms)
print "calculate_pi1: ", time.time() - start, "s"
start = time.time()
Pi2 = calculate_pi2(nTerms)
print "calculate_pi2: ", time.time() - start, "s"

print 'Terms : ' , nTerms
print '   Pi1: ' , Pi1
print '   Pi2: ' , Pi2
print '   Pi : ' , math.pi


-- 
bhoel at web.de / http://starship.python.net/crew/bhoel/
        It is unlawful to use this email address for unsolicited ads
        (USC Title 47 Sec.227). I will assess a US$500 charge for
        reviewing and deleting each unsolicited ad.



More information about the Python-list mailing list