Figure 9-12. Example plot (detail) with linear interpolation
Therefore, let us repeat the complete exercise, this time using cubic splines:
In [ 50 ]: ipo = spi.splrep(x, f(x), k= 3 )
iyd = spi.splev(xd, ipo)
Now, the detailed subinterval in Figure 9-13 shows a graphically perfect interpolation:
In [ 51 ]: plt.plot(xd, f(xd), ‘b’, label=‘f(x)’)
plt.plot(xd, iyd, ‘r.’, label=‘interpolation’)
plt.legend(loc= 0 )
plt.grid(True)
plt.xlabel(‘x’)
plt.ylabel(‘f(x)’)
Figure 9-13. Example plot (detail) with cubic spline interpolation
Numerically, the interpolation is not perfect, but the MSE is really small:
In [ 52 ]: np.allclose(f(xd), iyd)
Out[52]: False
In [ 53 ]: np.sum((f(xd) - iyd) ** 2 ) / len(xd)
Out[53]: 1.1349319851436252e-08
INTERPOLATION
In those cases where spline interpolation can be applied you can expect better approximation results compared to
a least-squares regression approach. However, remember that you need to have sorted (and “nonnoisy”) data and
that the approach is limited to low-dimensional problems. It is also computationally more demanding and might
therefore take (much) longer than regression in certain use cases.