Python 为收敛到pi定义错误列表
我是python新手,我正试图基于一个定义的术语,对一系列向pi的收敛进行建模。我已经创建了一个列表,在每次迭代时返回pi的近似值,但是,我正在努力创建一个列表,返回pi和math.pi的近似值之间的差值。我知道代码目前只是循环一个pi值的错误项,我不知道如何循环n个pi值。我相信这是一个简单的修复,我只是忽略了,所以任何帮助将不胜感激。 这是我的密码:Python 为收敛到pi定义错误列表,python,Python,我是python新手,我正试图基于一个定义的术语,对一系列向pi的收敛进行建模。我已经创建了一个列表,在每次迭代时返回pi的近似值,但是,我正在努力创建一个列表,返回pi和math.pi的近似值之间的差值。我知道代码目前只是循环一个pi值的错误项,我不知道如何循环n个pi值。我相信这是一个简单的修复,我只是忽略了,所以任何帮助将不胜感激。 这是我的密码: from math import pi from math import factorial def term_in_series_1(n)
from math import pi
from math import factorial
def term_in_series_1(n):
values=[]
for k in range (n, -1,-1): #Here we are creating a for loop starting at n, finishing at -1 with a stepsize of -1
value_of_term_n = 2 * 2**k * (factorial(k))**2 / factorial(2*k+1) #The loop uses this equation to calculate the value term of n for values in the range of n
values.append(value_of_term_n) #The append function allows each new value term of n to be added to the empty list "values" with length n
return values
def series_1(n):
approximation_for_pi = sum(term_in_series_1(n)) #This line is taking the sum of all the values in the series calulated in the previous function
return approximation_for_pi
def error_1(j):
values=[]
for i in range (j):
for k in range (n):
value_of_error_1 = pi - series_1(n) #The loop uses this equation to calculate the value term of n for values in the range of n
values.append(value_of_error_1) #The append function allows each new value term of n to be added to the empty list "values" with length n
return values
error_1(15)
此代码似乎是问题所在:
for i in range (j):
value_of_error_1 = pi - series_1(n)
您有一个迭代变量i
,但不知从何处引用n
。假设迭代变量应该是n
,下面是对代码的修改:
from math import pi, factorial
def term_in_series_1(n):
values = []
for k in range(n, -1, -1):
value_of_term_n = 2 * 2**k * factorial(k)**2 / factorial(2*k+1)
values.append(value_of_term_n)
return values
def series_1(n):
return sum(term_in_series_1(n))
def error_1(j):
errors = []
for n in range(j):
errors.append(pi - series_1(n))
return errors
print(error_1(10))
请提供预期的(MRE)。我们应该能够复制和粘贴一个连续的代码块,执行该文件,并再现您的问题以及跟踪问题点的输出。这让我们可以根据您的测试数据和期望的输出来测试我们的建议。这不应该作为一个输入错误来结束吗?我同意Barmar。