Approximation of the cosine function using the n first terms of a series

1

Data x real and n natural, compute an approximation for cos x through n first terms of the following series:

cos x = 1/1 - (x**2)/2! + (x**4)/4! - (x**6)/6! + ... + ((-1)**k)*(x**2k)/((2k)!)

My attempt to resolve:

import math

#x =1 #calcular o cosx
#k =1 #número de termos da série

k = int(input("Digite k: "))
x = float(input("Digite x: "))
soma =0.0
for i in range(0,k+1):
    soma += ((-1)**k)*(x**(2*k))/(math.factorial(2*k))

print(soma)

What is the implementation error? How to correct?

    
asked by anonymous 23.03.2018 / 18:50

1 answer

2

Your first problem is that when x = 0 , soma = 1 . So, you should initialize the sum with the value 1 and not 0. Then you are using i to iterate from 0 to k however, inside the loop you put k instead of i . Following these fixes, I suggest that the correct code be:

import math

#x =1 #calcular o cosx
#k =1 #número de termos da série

k = int(input("Digite k: "))
x = float(input("Digite x: "))
soma = 0.0

for i in range(0,k):
    soma = soma + ((-1) ** i) * (x ** (2 * i)) / (math.factorial(2 * i))

print(soma)
    
23.03.2018 / 21:15