Home > Back-end >  How do I make an infinite series using an equation?
How do I make an infinite series using an equation?

Time:09-23

I'm trying to make a function called cos_series that uses values x and nterms that gives me the sum of a series, using this equation 1 - x^2/2! x^4/4! - x^6/6! ...

This is my code so far,

def cos_series(x,nterms):
    lst = []
    lst2 = []
    for i in range(nterms):
        lst =[x**(2*i)/(math.factorial(i*2))]
    for i in range(nterms):
        lst2 =[(x**(2*i)/(math.factorial(i*2)))*-1]
    return sum(lst2[1::2]   lst[::2])

cos_series(math.pi/3,3)

The return value should equal 0.501796 but I'm having trouble reaching it, can anyone help?

CodePudding user response:

Your code seems to work just fine.

Your logic works with just:

def cos_series(x, n):
    return sum((-1 if (i % 2) else 1) * x**(i*2) / math.factorial(i*2) for i in range(n))

Generating the sum of the series in one go and avoiding the computation of values you don't use.

(note that, after you changed your question, your code in fact returns 0.501796201500181 - which is the value you expected; there's no issue?)

CodePudding user response:

I would opt for creating the sum as you go rather than making lists (unless you need the list for some other reason). This will be a little easier to understand to others reading it and be a little more memory friendly (not that the lists should ever get huge).

def cos_series(x,nterms):
    start = 1
    factor = -1
    
    for n in range(1, nterms):
        i = n * 2
        start  = factor * ((x ** i) / math.factorial(i))
        factor *= -1 # alternate subtraction and addition
    return start

cos_series(math.pi/3,3)
# 0.501796201500181

Computing more iterations will eventually get down to the true value of cos(π/3) which is 0.5:

cos_series(math.pi/3,15)
# 0.5000000000000001

CodePudding user response:

You don't need to use math.factorial() and you don't need to store the terms in a list. Just build the numerator and denominator as you go and add up them up.

By producing the numerator and denominator iteratively, your logic will be much easier to manage and debug:

def cos(x,nTerms=10):
    result      = 0
    numerator   = 1
    denominator = 1
    for even in range(2,nTerms*2 1,2):          # nTerms even numbers
        result       = numerator / denominator  # sum of terms            
        numerator   *= -x*x                     #  /- for even powers of x
        denominator *= even * (even-1)          # factorial of even numbers
    return result

print(cos(3.141592653589793/3,3)) # 0.501796201500181
  • Related