gpt4 book ai didi

python - 在误差范围内逼近 pi

转载 作者:行者123 更新时间:2023-11-28 22:00:31 26 4
gpt4 key购买 nike

首先,这就是问题所在。

The mathematical constant π (pi) is an irrational number with value approximately 3.1415928... The precise value of π is equal to the following infinite sum: π = 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ... We can get a good approximation of π by computing the sum of the first few terms. Write a function approxPi() that takes as a parameter a floating point value error and approximates the constant π within error by computing the above sum, term by term, until the absolute value of the difference between the current sum and the previous sum (with one fewer terms) is no greater than error. Once the function finds that the difference is less than error, it should return the new sum. Please note that this function should not use any functions or constants from the math module. You are supposed to use the described algorithm to approximate π, not use the built-in value in 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

关于python - 在误差范围内逼近 pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14803742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com