I am trying to use the Maclaurin series to estimate the sine of a number. This is my function:
from math import sin, factorial
import numpy as np
fac = np.vectorize(factorial)
def sin_x(x, terms=10):
""" Calcul une approximation de sin(x) en utlisant
un nombre donné de termes de la serie de Maclaurin"""
n = np.arange(terms)
return np.sum[((-1)**n)(x**(2*n 1)) / fac(2*n 1)]
if __name__ == "__main__":
print("Valeur actuelle:", sin(5)) # En utilisant la fonction sinus de la librairie math
print("N (terms)\tMaclaurin\tErreur")
for n in range(1, 6):
maclaurin = sin_x(5, terms=n)
print(f"{n}\t\t{maclaurin:.03f}\t\t{sin(10) - maclaurin:.03f}")
and this is the error I get
PS C:\Users\tapef\Desktop\NUMPY-TUT> python maclaurin_sin.py
Valeur actuelle: -0.9589242746631385
N (terms) Maclaurin Erreur
Traceback (most recent call last):
File "C:\Users\tapef\Desktop\NUMPY-TUT\maclaurin_sin.py", line 20, in <module>
maclaurin = sin_x(5, terms=n)
File "C:\Users\tapef\Desktop\NUMPY-TUT\maclaurin_sin.py", line 12, in sin_x
return np.sum[((-1)**n)(x**(2*n 1)) / fac(2*n 1)]
TypeError: 'numpy.ndarray' object is not callable
How do I get rid of this error? Thanks
I've tried to use brackets instead of parenthetis.
CodePudding user response:
You forgot the multiplication between (-1)**n)
and (x**(2*n 1)
. Furthermore, np.sum()
needs to be called as a function, so your return statement becomes:
return np.sum(((-1)**n)*(x**(2*n 1)) / fac(2*n 1))