For the nodes $x_{0}=-1,$ $x_{1}=1,$ $x_{2}=3$ and $x_{3}=5,$ and the function $$f\left(x\right)=\sin\left(\dfrac{\pi}{6}x\right)$$ if the cubic natural spline that interpolates these nodes is $$s(x)=\begin{cases} s_{1}(x)=a\,(x+1)^{3}+b\,(x+1)^{2}+c\,(x+1)+d & \mathrm{if\;}x\in\left[-1,1\right]\\ s_{2}(x)=e\,(x-1)^{3}+f\,(x-1)^{2}+g\,(x-1)+h & \mathrm{if\;}x\in\left[1,3\right]\\ s_{3}(x)=i\,(x-3)^{3}+j\,(x-3)^{2}+k\,(x-3)+l & \mathrm{if\;}x\in\left[3,5\right] \end{cases}$$
We need the values of the function at the nodes to calculate the spline
The following conditions must be met:
The curve must go through all the points $$ s_{1}(-1)=-\dfrac{1}{2},\;s_{1}(1)=\dfrac{1}{2},\;s_{2}(1)=\dfrac{1}{2},\;s_{2}(3)=1,\;s_{3}(3)=1,\;s_{3}(5)=1/2. $$
The first and second derivatives must be the same for the intermediate points $$ s'_{1}(1)=s'_{2}(1),\;s'_{2}(3)=s'_{3}(3),\; s''_{1}(1)=s''_{2}(1),\;s''_{2}(3)=s''_{3}(3) $$
We have
Let's calculate the first derivatives
and the second ones
and the equations are:
And we have a linear system of 12 equations to calculate 12 unknowns, which expressed in matrix form is
The solution of this system is $a=-1/120$, $b=0$, $c=8/15$, $d=-1/2$, $e=-1/48$, $f=-1/20$, $g=13/30$, $h=1/2$, $i=7/240$, $j=-7/40$, $k=-1/60$ and $l=1$. Therefore the cubic spline is
This is an example of what a cubic spline is, it is not an example of an efficient spline construction algorithm. In the usual algorithm, the shape of the polynomials of degree 3 in each subinterval is different from the one here and it seeks that the linear system is tridiagonal, that is, the matrix of coefficients only has elements in three diagonals: the main one, the one above the main diagonal and the one that is below. Tridiagonal systems have specific storage and resolution algorithms that are simpler than the ones for full coefficient matrices.
Regardless of the number of nodes, when constructing a cubic spline, two equations are always missing. Two additional equations are needed that are usually applied to the nodes of the edges of the interval and for this reason they are boundary conditions. Depending on them the spline is called
Since the point $2$ is in the interval $[1,3]$ we will use the polynomial
As $f(2)=\sin\left(\dfrac{\pi}{6}(2)\right)=\sin\left(\dfrac{\pi}{3}\right)=0.86603$
And, with the same number of nodes, in this case, the error is less than for the Lagrange interpolation polynomial with 4 nodes.
Let's also compare the result for a function where the Lagrange interpolation fails because the degree of the polynomial is very high and the interpolation polynomial oscillates.
We can see that the cubic spline gives here a very good approximation