Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

Gauss-Legendre Algorithm in python

I need some help calculating Pi. I am trying to write a python program that will calculate Pi to X digits. I have tried several from the python mailing list, and it is to slow for my use. I have read about the Gauss-Legendre Algorithm, and I have tried porting it to Python with no success.

I am reading from Here, and I would appreciate any input as to where I am going wrong!

It outputs: 0.163991276262

from __future__ import division
import math
def square(x):return x*x
a = 1
b = 1/math.sqrt(2)
t = 1/4
x = 1
for i in range(1000):
    y = a
    a = (a+b)/2
    b = math.sqrt(b*y)
    t = t - x * square((y-a))
    x = 2* x

pi = (square((a+b)))/4*t
print pi
raw_input()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. You forgot parentheses around 4*t:

    pi = (a+b)**2 / (4*t)
    
  2. You can use decimal to perform calculation with higher precision.

    #!/usr/bin/env python
    from __future__ import with_statement
    import decimal
    
    def pi_gauss_legendre():
        D = decimal.Decimal
        with decimal.localcontext() as ctx:
            ctx.prec += 2                
            a, b, t, p = 1, 1/D(2).sqrt(), 1/D(4), 1                
            pi = None
            while 1:
                an    = (a + b) / 2
                b     = (a * b).sqrt()
                t    -= p * (a - an) * (a - an)
                a, p  = an, 2*p
                piold = pi
                pi    = (a + b) * (a + b) / (4 * t)
                if pi == piold:  # equal within given precision
                    break
        return +pi
    
    decimal.getcontext().prec = 100
    print pi_gauss_legendre()
    

Output:

3.141592653589793238462643383279502884197169399375105820974944592307816406286208
    998628034825342117068

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...