code optimization (calc PI) / New Algorithme for PI

Nick Craig-Wood nick at craig-wood.com
Fri Jan 5 11:30:04 CET 2007


Michael M. <michael at mustun.ch> wrote:
>  Yes, this "gmpy" sounds good for calc things like that.
>  But not available on my machine.
>  ImportError: No module named gmpy

Sorry, I should have said - you'll need to download that from

  http://gmpy.sourceforge.net/

>  Anyway, thanks for posting. This gmpy module can be very intersting.
>  But right now, the focus was, if it's possible to translate a strange C 
>  code into Python. And it is. Sure ;-)
> 
>  Maybe, someone can also translate a very simple algorithm for calc a 
>  range of PI in Python. (Available Code for C.)
>  http://crd.lbl.gov/~dhbailey/

Here are some more pi calculation methods.  You'll need the FixedPoint
class in my last posting, or you cah use gmpy mpf~s also.

_1 = FixedPoint(1)
# or
_1 = gmpy.mpf(1, bits)
# or (for testing)
_1 = 1.0

_3 = _1 * 3

def arctan(x):
    """
    Calculate arctan(x)
    
    arctan(x) = x - x**3/3 + x**5/5 - ... (-1 <= x <= 1)
    """
    total = x
    power = x
    divisor = 1
    old_delta = None
    while 1:
        power *= x
        power *= x
        power = -power
        divisor += 2
        old_total = total
        total += power / divisor
        delta = abs(total - old_total)
        if old_delta is not None and delta >= old_delta:
            break
        old_delta = delta
    return total

def pi_machin():
    return 4*(4*arctan(_1/5) - arctan(_1/239))

def pi_ferguson():
    return 4*(3*arctan(_1/4) + arctan(_1/20) + arctan(_1/1985))

def pi_hutton():
    return 4*(2*arctan(_1/3) + arctan(_1/7))

def pi_gauss():
    return 4*(12*arctan(_1/18) + 8*arctan(_1/57) - 5*arctan(_1/239))

def pi_euler():
    return 4*(5*arctan(_1/7) + 2*arctan(_3/79))


-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list