Perform third-order spline interpolation using the interp1d method ** of ** scipy.interpolate.
Example: Consider $ y = 1 / (1 + x ^ 2) $. Sample and interpolate the 11-point data set $ (x_i, y_i) $. This function does not work with Lagrange interpolation (see Qiita article).
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
x =np.linspace(-5,5,num=11)
y = 1.0/(1.0+x**2)
f_line = interp1d(x, y)
f_CS = interp1d(x, y, kind='cubic') #Execute 3rd spline interpolation!
#for plot
xnew =np.linspace(-5,5,num=51)
plt.plot(x, y, 'o', xnew, f_CS(xnew), '-')
plt.legend(['Raw data','Lagrange', 'Cubic spline'], loc='best')
plt.xlim([-6, 6])
plt.ylim([0, 1.4])
plt.show()
11 data points sampled by blue. The orange line is spline interpolated.
As shown in the figure below, Lagrange polynomial does not interpolate this function well.
11 data points sampled by blue. The orange line is spline-interpolated and the green line is Lagrange-interpolated, causing unnatural vibration near both ends.