python中的高斯 - 勒让德算法

Lob*_*obe 14 python algorithm pi

我需要一些帮助来计算Pi.我正在尝试编写一个将Pi计算为X位数的python程序.我已经尝试过python邮件列表中的几个,这对我的使用来说很慢.我已经阅读了有关Gauss-Legendre算法的内容,我尝试将其移植到Python但没有成功.

我正在读这里,我很感激我输入错误的地方!

输出: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()
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 26

  1. 你忘记了括号4*t:

    pi = (a+b)**2 / (4*t)
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您可以使用decimal更高精度执行计算.

    #!/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()
    
    Run Code Online (Sandbox Code Playgroud)

输出:

3.141592653589793238462643383279502884197169399375105820974944592307816406286208\
    998628034825342117068
Run Code Online (Sandbox Code Playgroud)

  • @tvanfosson:我发布了使用`decimal`的版本.它允许任意精度. (3认同)