Search code examples
pythonnumpyinterpolationpolynomials

Obtaining a list of the coefficients from the Lagrange interpolation in python


I tried coding the Lagrange interpolation in python so that it returns a list of the polynomial coefficients but when I display the curve it isn't at all what I expect. Most people coding this interpolation only evaluate it in one point but I want to obtain a list of the coefficients.

from math import *
import numpy as np
import matplotlib.pyplot as plt

def P(l,x:float):   # l is the list of coeffcients from lowest to highest degree
    res=0
    for n,i in enumerate(l):
        res+=i*x**n    # evaluate the equation in x
    return res

def Lagrange(xtab,ytab):    # return the Lagrange interpolation
    X=np.poly1d([1,0])
    P=0
    for i in range(len(ytab)):
        Li=1
        for j in range(len(ytab)):
            if i==j:
                continue
            else :
                Li=Li*((X-xtab[j])/(xtab[i]-xtab[j]))
        P+=Li*ytab[i]
    return Li

def points(l,N,h):   # return  a list of points of a known polynomial randomized a little by h
    xtab=np.linspace(-10,10,N)
    ytab=np.zeros(N)
    for k,x in enumerate(xtab):
        ytab[k]=P(l,x)
    for i,y in enumerate(ytab):
        ytab[i]= y + np.random.uniform(-h,h)
    return xtab,ytab


N=20
xtab,ytab=points([3,0,-2],N,0.2)


L=Lagrange(xtab,ytab)
ylagrange=np.polyval(L,xtab2)

plt.figure()
plt.plot(xtab1,ytab1)
plt.plot(xtab2,ylagrange)
plt.show()

When I display the curves, it doen't follow the points given like it should. The code does give an equation so I don't really know what goes wrong.


Solution

  • Ah, but you were so close!

    Just change

    return Li
    

    to

    return P
    

    Then, if you want your actual equation, you can put

    print( L )
    

    after your line L=Lagrange(xtab,ytab).

    Your plotting needs some minor correction:

    N=20
    xtab,ytab=points([3,0,-2],N,0.2)
    L=Lagrange(xtab,ytab)
    ylagrange=np.polyval(L,xtab)
    plt.figure()
    plt.plot(xtab,ytab,'o')
    plt.plot(xtab,ylagrange)
    plt.show()
    

    Thus: enter image description here