我需要一些帮助来计算 Pi。我正在尝试编写一个 python 程序来将 Pi 计算为 X 位数字。我已经尝试了 python 邮件列表中的几个,但它对我的使用来说太慢了。
我读过有关高斯-勒让德算法 http://en.wikipedia.org/wiki/Gauss-Legendre_algorithm,我尝试将其移植到Python但没有成功。
我正在阅读Here http://www.geocities.com/hjsmithh/Pi/Gauss_L.html,对于我哪里出错的任何意见,我将不胜感激!
它输出: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()
-
你忘记了括号4*t
:
pi = (a+b)**2 / (4*t)
-
您可以使用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()
Output:
3.141592653589793238462643383279502884197169399375105820974944592307816406286208\
998628034825342117068
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)