How to implement the cosine function using Taylor series in Python?

Asked

Viewed 783 times

1

Guys, I have the following problem: EXERCÍCIO

Until then I made the following code:

import math

def cos(x, n):

    soma = 1
    formula = (((-1)**n)*(x**2*n))/math.factorial(2*n)
    for i in range(n):
        soma += formula
    return soma

Can anyone say if it is correct? If not, how do I correct?

  • An option to avoid calculation ((-1)**n)is to make: sinal = 1 outside the loop and inside the loop make: sinal = -sinal.

2 answers

3


It’s not (but almost). The way you did:

def cos(x, n):

    soma = 1
    formula = (((-1)**n)*(x**2*n))/math.factorial(2*n)
    for i in range(n):
        soma += formula
    return soma

The value of formula shall be evaluated only once, with n equal to the parameter passed. You need to evaluate this value for each item in your sequence. Otherwise, your formula must depend on the value of i (which is the k in the sum), not of n. And if you’re gonna do the range starting at 0, you should not start the value of soma with 1, but with 0, because it is the neutral element of the addition.

As for the formula, there is only one operator priority problem. When you write x**2*n will be x²n and not x2n as expected; to circumvent this you should add the parentheses.

import math

def cos(x, n):
  formula = lambda k: (-1)**k * x**(2*k) / math.factorial(2*k)
  soma = 0

  for k in range(n+1):
    soma += formula(k)

  return soma

See working on Repl.it | Ideone

To check if it is right, just compare the returned value with the function math.cos:

assert math.isclose(cos(0.5, 10), math.cos(0.5))
assert math.isclose(cos(-0.5, 10), math.cos(-0.5))
assert math.isclose(cos(0.0, 10), math.cos(0.0))
assert math.isclose(cos(1.0, 10), math.cos(1.0))

If a AssertionError is because some value went wrong.

Using generators and function sum, its function could be reduced to one line:

import math

def cos(x, n):
  return sum((-1)**k * x**(2*k) / math.factorial(2*k) for k in range(n+1))

This process is what we know by Taylor series expansion and I’ve answered this for the sine calculation in:

On the process of associating a mathematical series with programming structures, you can read:

  • Thanks!!! I even found your answer, but I had already posted here, thanks even.

-1

The only thing I would do is to isolate the "x²k"

formula = (((-1)**n)*(x**2*n))/math.factorial(2*n) # o teu
formula = (((-1)**n)*(x**(2*n)))/math.factorial(2*n) #isolado

Thus avoids any misinterpretation or ambiguity.

  • There are more problems with his code. The calculation is out of the loop. It’s not just about matching the precedence. The @Woss answer is correct.

Browser other questions tagged

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