简体   繁体   中英

Finding the sum of the terms of a sequence in python

i have this function which calculates the sum of the terms of a sequence.

def sum_sequence(n, term)

    i, sum = 2, term(1)
    while i <= n:
        sum += term(i)
        i += 1
    return sum

Afterward i am given this 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(________, _________)

and i need it to return the sum of the terms of the sequence given depending on the n given using only the blanks (_______) provided

You can build the terms of the series like this:

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

Example output:

print(terms(4))
# [4.0, -1.3333333333333333, 0.8, -0.5714285714285714]

Then use sum to add 'em up:

estimate_of_pi = sum(terms(100))

print(estimate_of_pi)
# 3.131592903558552

To compute a single term (starting at n=0):

def single_term(n):
    num = 4.0 * ((-1)**n)
    den = 1 + n*2
    return num / den

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM