首先,这就是问题所在。
数学常数π(pi)是一个无理数,其数值约为3.1415928。π的精确值等于以下无限和:π=4/1-4/3+4/5-4/7+4/9-4/11+…通过计算前几个项的和,我们可以得到π的一个很好的逼近。编写一个函数approxPi(),该函数将浮点值误差作为参数,并通过逐项计算上述和,在误差范围内逼近常量π,直到当前和与前一和之间的差的绝对值(加上一个较少的项)不大于误差。一旦函数发现差值小于误差,它就应该返回新的和。请注意,此函数不应使用来自数学模块的任何函数或常量。您应该使用所描述的算法来近似π,而不是使用Python中内置的值。
如果有人能帮助我理解问题所在,我会非常感激的,因为我已经读过很多次了,但仍然不能完全理解它的意思。我翻阅了我的教科书,发现了一个用e的无限和近似e的类似问题: 1/0!+ 1/1!+ 1/2!+1/3!+…
def approxE(error):
import math
'returns approximation of e within error'
prev = 1 # approximation 0
current = 2 # approximation 1
i = 2 # index of next approximation
while current-prev > error:
#while difference between current and previous
#approximation is too large
#current approximation
prev = current #becomes previous
#compute new approximation
current = prev + 1/math.factorial(i) # based on index i
i += 1 #index of next approximation
return current我试图以此为我的程序建模,但我不觉得我离解决方案越来越近了。
def approxPi(error):
'float ==> float, returns approximation of pi within error'
#π = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
prev = 4 # 4/1 = 4 : approx 0
current = 2.6666 # 4/1 - 4/3 = 2.6666 : approx 1
i = 5 # index of next approx is 5
while current-prev > error:
prev = current
current = prev +- 1/i
i = i +- 2
return current成功的程序应该返回
approxPi(0.5) = 3.3396825396825403,approxPi(3.3396825396825403)= 3.1659792728432157
再一次,任何帮助都将不胜感激。我只想明白我在这方面做错了什么。
发布于 2013-02-10 23:24:52
如果您试图使用该系列来近似pi,请从写出以下几个术语开始:
π = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
0 1 2 3 4 5 ...然后编写一个函数,返回本系列的第n项:
def nth_term(n):
return 4 / (2.0 * n + 1) * (-1) ** n从这里开始,代码非常通用:
def approximate_pi(error):
prev = nth_term(0) # First term
current = nth_term(0) + nth_term(1) # First + second terms
n = 2 # Starts at third term
while abs(prev - current) > error:
prev = current
current += nth_term(n)
n += 1
return current它似乎适用于我:
>>> approximate_pi(0.000001)
3.1415929035895926发布于 2013-02-10 23:22:09
有几个问题:
i = i +- 2不做你想做的事,也不知道它是什么。
正确的代码应该类似于(有很多方法):
if i < 0:
i = -(i-2)
else:
i = -(i+2)同样的情况也适用于:
current = prev +- 1/i它应该是:
current = prev + 4.0/i或者其他的东西,具体取决于存储在i中的内容。当心!在python2中,除非您从将来导入新的部门,否则您必须键入4.0,而不仅仅是4。
就我个人而言,我更倾向于变量、除数的绝对值和符号,以便在每次迭代中:
current = current + sign * 4 / d
d += 2
sign *= -1好多了!
( B)循环结束时应检查错误的绝对值:
类似于:
while abs(current-prev) > error:因为当前值跳过目标值,一个值更大,一个值更小,所以一个错误是正的,一个是负的。
发布于 2013-02-10 23:45:56
我是这样做的:
def approxPi(error):
# pi = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
value = 0.0
term = 1.0e6
i = 1
sign = 1
while fabs(term) > error:
term = sign/i
value += term
sign *= -1
i += 2
return 4.0*value
print approxPi(1.0e-5)https://stackoverflow.com/questions/14803742
复制相似问题