import numpy as np
x = np.array([1,2,6,11])
y = np.array([-3,-29,-33,-90])
# construct the Lagrange basis polynomials
nplus1 = len(x)
xx = np.linspace(0,12,400) # evaluation points
l = []
for k in range(nplus1):
# construct l_k evaluated at xx
lk = np.ones_like(xx)
for j in range(nplus1):
if j!=k:
lk *= (xx-x[j])/(x[k]-x[j])
l.append(lk)
type(l),len(l)
(list, 4)
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
plt.axhline(0,color='k',alpha=.25)
#plt.plot(x,y,'o')
plt.plot(x,np.zeros_like(x),'ko')
for xk in x:
plt.axvline(xk,alpha=0.2)
for lk in l:
plt.plot(xx,100*lk)
plt.savefig('lagrange_polys.pdf')
# now construct the interpolating polynomial
p = np.zeros_like(xx)
for k in range(nplus1):
p += y[k]*l[k]
# and plot it
plt.plot(x,y,'o')
#plt.plot(x,np.zeros_like(x),'ko')
for xk in x:
plt.axvline(xk,alpha=0.2)
plt.plot(xx,p)
plt.savefig('lagrange_polys.pdf')
A = np.empty((nplus1,nplus1))
for k in range(nplus1):
# write the kth column
A[:,k] = x**k # RHS is b_k
np.array(A,dtype=int)
array([[ 1, 1, 1, 1], [ 1, 2, 4, 8], [ 1, 6, 36, 216], [ 1, 11, 121, 1331]])
c = np.linalg.solve(A,y)
c
array([ 40.38666667, -53.31111111, 10.54 , -0.61555556])
# construct p
p = np.zeros_like(xx)
for k in range(nplus1):
p += c[k]*xx**k
# and plot it
plt.plot(x,y,'o')
#plt.plot(x,np.zeros_like(x),'ko')
for xk in x:
plt.axvline(xk,alpha=0.2)
plt.plot(xx,p)
plt.savefig('interpolant_using_monomial_basis.pdf')