Lagrange method, find polynomial with Python

3.7k Views Asked by At

I have to find the Langrange polynomium for exp(-x)*cos(4*pi*x) for x in(0,3). I have found a python code to plot these approximation as a graph, but how can I use these to find the approximated Langrange polynomium in the interval x in(0,3)? Here is the code:

enter image description here

2

There are 2 best solutions below

0
On

I think you can just extract the coefficients of the polynomial. This is from https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.lagrange.html

Interpolate f(x) = x^3  
by 3 points.
>>>

>>> from scipy.interpolate import lagrange
>>> x = np.array([0, 1, 2])
>>> y = x**3
>>> poly = lagrange(x, y)

Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly, it is given by
>>>

>>> from numpy.polynomial.polynomial import Polynomial
>>> Polynomial(poly).coef
array([ 3., -2.,  0.])
5
On

If you wish to know the coefficients of the polynomial, you can simply print it, e.g.

from scipy.interpolate import lagrange
from numpy import exp, cos, linspace, pi
f = (lambda x: exp(-x) * cos(4 * pi * x))
x = linspace(0, 3, 5)
print(lagrange(x, f(x)))

will give

        4         3         2
0.6189 x - 4.046 x + 8.594 x - 6.394 x + 1