import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as pt
if True:
def f(x):
return np.exp(1.5*x)
def df(x):
return 1.5*np.exp(1.5*x)
else:
def f(x):
return np.sin(4*x)
def df(x):
return 4*np.cos(4*x)
x = np.linspace(0, 1, 1000)
pt.plot(x, f(x))
Fix some parameters:
degree = 2
h = 1
nodes = np.linspace(0, h, degree+1)
nodes
Build the Vandermonde matrix:
V = np.array([
nodes**i
for i in range(degree+1)
]).T
V
Now find the interpolation coefficients as coeffs
:
coeffs = la.solve(V, f(nodes))
interp = 0*x
for i in range(degree+1):
interp += coeffs[i] * x**i
pt.plot(x, f(x), "--", color="gray", label="$f$")
pt.plot(x, interp, color="red", label="Interpolant")
pt.plot(nodes, f(nodes), "o")
pt.legend(loc="best")
Now evaluate the derivative as interp_deriv
:
interp_deriv = 0*x
for i in range(1, degree+1):
interp_deriv += coeffs[i] * i * x**(i-1)
pt.plot(x, interp_deriv, color="red", label="Interpolant")
pt.plot(x, df(x), "--", color="gray", label="Derivative")
pt.legend(loc="best")