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

Asked

Viewed 668 times

0

Data x real and n natural, calculate an approximation to 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 at solution:

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?

1 answer

2

Your first problem is that when x = 0, soma = 1. Therefore, it should initialize sum with the value 1 and not 0. Next, you are using i to iterate from 0 to k however, within the placed loop k instead of i. Following these corrections, I suggest the correct code is:

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)
  • thanks. I am trying to solve various problems to get the hang of programming!

  • I think there is still something wrong with the code. For example, cos1 =0.54 but the program calculates as -1.6534391534391533e-06 with k=5

  • when k=0, the sum already gives 1 in the for loop. if you sum =1, you will be 1+1

  • sum = 0.0 same!

  • I still think that soma = 1 as cos(0) = 1.

  • When using k = 0 is making an approximation to the cosine with 0 iterations, so you cannot expect a result close to the real

  • However, I am not a mathematician or anything like that, so take this answer carefully

  • I just commented for you to edit the sum amount and I accept the answer!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.