[英]Finding the sum of the terms of a sequence in python
我有这个 function 计算序列项的总和。
def sum_sequence(n, term)
i, sum = 2, term(1)
while i <= n:
sum += term(i)
i += 1
return sum
之后我得到了这个 function:
def paei_pi(n):
""" the sum of n terms of this specific sequence
4, -4/3, 4/5, -4/7, 4/9, -4/11, 4/13, ... etc.
n -- positive number >= 1
returns the sum of the terms 1 through n.
Examples:
>>> paei_pi(1)
4.0
>>> paei_pi(2)
2.666666666666667
>>> paei_pi(3)
3.466666666666667
>>> paei_pi(1000)
3.140592653839794
>>> paei_pi(10000)
3.1414926535900345
"""
def (____):
return _____________________
return sum_sequence(________, _________)
我需要它返回给定的序列项的总和,具体取决于仅使用提供的空白 (_______) 给出的 n
您可以像这样构建系列的条款:
def terms(n):
t = []
num = 4.0
den = 1.0
for i in range(n):
t.append(num / den)
# set up the next term
num = -num # sign flip
den += 2 # next odd demoninator
return t
示例 output:
print(terms(4))
# [4.0, -1.3333333333333333, 0.8, -0.5714285714285714]
然后使用sum
将它们相加:
estimate_of_pi = sum(terms(100))
print(estimate_of_pi)
# 3.131592903558552
计算单个项(从 n=0 开始):
def single_term(n):
num = 4.0 * ((-1)**n)
den = 1 + n*2
return num / den
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.