簡體   English   中英

在 python 中查找序列項的總和

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM