根据印度数学家Srinivasa Ramanujan找到的公式,编写一个函数estimatePi()
来估计并返回Pi的值。它应该使用while循环来计算求和的项,直到最后一项小于1e-15。Pi的估算公式如下:根据Ramanujam的估算
(对不起,我无法上传图片)
def estimatePi():
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
k=0
final=0
pi=0
while pi<1e-15:
a=factorial(4*k)
b=(1103+26390*k)
c=factorial(k)
d=c**4
e=396**(4*k)
f=2*math.sqrt(2)/9801
final+=(a*b*f)/(d*e)
k+=1
pi=1/final
return pi
我的问题是:预期答案是=3.14159265359我的答案是=3.14159273001
我找不到我的错误:有人能帮我解决这个问题吗?
发布于 2012-08-09 17:32:26
你的回答是正确的。浮点数具有problems with accuracy,特别是对于小数点后的大量数字;以及在计算非精确值时。
你可以从你的答案中看到,它已经正确地估计了小数点后5位的π的值。
发布于 2015-12-26 11:12:41
我的朋友,你的代码有几处地方出了问题。首先,在您的代码中,请记住变量pi的任何形状或形式都不等于final。您正在计算一个不会迭代的while循环,因为pi显然是一个大于1e-15的数字。所以简单地说,你的代码只是在k=0上计算你的公式,然后它就停止了。因此,这里有一种可能的方法:
def estimatePi():
import math
def factorial(n):
if n == 0:
return 1
else:
return math.factorial(n)
k=1 # we want it at k=1 not 0 since we already have k=0 as Final
Final=0.31830987844 #this is the value at k=0, the first value
while Final>1e-15: """ Note that 1e-15 is the limiting value and we want all b values that are less than 1e-15. k=2 is the final k value where b has the last smaller number than 1e-15."""
b=(2*math.sqrt(2)/9801)*(factorial(4*k)*(1103+26390*k))/((factorial(k)**4)*(396**(4*k)))
Final=Final+b
k=k+1
return 1/Final
print estimatePi()
#This gives you the number you are looking for ---3.14159265359.
发布于 2016-12-04 09:54:09
这是我的代码。它返回与所需结果相同的结果:
import math
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def estimatePi():
f=2*math.sqrt(2)/9801
k=0
RHS = 0
while True:
num = factorial(4*k)*(1103+26390*k)
den = (factorial(k))**4 * 396**(4*k)
a = f*num/den
RHS += a
if a < 1e-15: break
k+=1
return 1/RHS
https://stackoverflow.com/questions/11880131
复制相似问题