Lagrange Demo

In [37]:
import numpy as np
import matplotlib.pyplot as plt

Some Data

In [38]:
X = [1, 3, 4.6, 5, 6]
Y = [3, 6, 3, 2, 5]

Define the Lagrange basis functions

In [39]:
def L(i, x):
    num = 1.
    denom = 1.
    xi = X[i]
    for k,xk in enumerate(X):
        if k!=i:
            num *= x - xk
            denom *= xi - xk
    return num / denom

Plot the Lagrange basis functions

In [40]:
# Create an array of 100 x-values for plotting
xx = np.linspace(X[0], X[-1], 100)

plt.figure(1, figsize=[10,6])
c = ['red', 'blue', 'green', 'brown', 'orange']
#plt.plot(X,Y,'ko')  # points
plt.plot([X[0], X[-1]],[0,0],'-', color='lightgray')  # x-axis
for i in range(len(X)): 
    plt.plot(xx,L(i,xx),'-', color=c[i])
    plt.plot(X[i], [1], 'ks')  # polynomial
plt.xlabel('x')
plt.title('Lagrange Basis Functions');
In [43]:
plt.figure(1, figsize=[10,10])
n = len(X)
for i in range(n): 
    plt.subplot(5,1,i+1)
    plt.plot([X[0], X[-1]],[0,0],'-', color='lightgray')  # x-axis
    plt.plot(xx,Y[i]*L(i,xx),'-', X,Y,'o')  # polynomial, and points
    plt.ylabel(r'$y_'+str(i)+' \, L_'+str(i)+'(x)$')
    if i==0:
        plt.title('Weighted Lagrange Basis Functions');
plt.xlabel('x'); plt.tight_layout();
In [34]:
plt.figure(1, figsize=[10,6])
c = ['red', 'blue', 'green', 'brown', 'orange']
plt.plot(X,Y,'ko')  # points
plt.plot([X[0], X[-1]],[0,0],'-', color='lightgray')  # x-axis
for i in range(len(X)): 
    plt.plot(xx,Y[i]*L(i,xx),'-', color=c[i])  # polynomial
plt.xlabel('x')
plt.title('Weighted Lagrange Basis Functions');

Define the Interpolating Polynomial

$$ P(x) = \sum_{i=1}^{n} L_i (x) y_i $$
In [35]:
def P(x):
    '''
     p = P(x)
     
     Evaluates the Langrange polynomial at x, based on the
     Lagrange basis functions, L, and corresponding y-coords, Y.
     Both L and Y are assumed to be globally defined.
    '''
    n = len(Y)
    
    val = 0.
    for i,y in enumerate(Y):
        val += L(i,x) * y
        
    return val

Plot the Lagrange polynomial

In [36]:
plt.figure(2, figsize=[10,6])
plt.plot(xx, P(xx), '-')
plt.plot(X,Y,'o');
plt.title('Interpolating Lagrange Polynomial');
In [ ]: