1
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:
An option to avoid calculation
((-1)**n)
is to make:sinal = 1
outside the loop and inside the loop make:sinal = -sinal
.– anonimo