首先,这就是问题所在。
数学常数π(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(0.05)=3.1659792728432157
再次感谢您的帮助。我只是想知道我在这件事上做错了什么。
如果您试图使用该系列来近似圆周率,请首先写出几个术语:
π = 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
有几个问题:
A) 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:
因为当前值跳过了目标值,一个值越大,一个越小,所以一个错误是正的,一个是负的。
以下是我的操作方法:
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)