Example for interpolation with piecewise cubic functions

Contents

Function 1/(1+x^2) on [-5,5] with 7 equidistant nodes

We compute the function values and the derivatives at the nodes.

We will use 1000 equidistant points xe on [-5,5] for plotting and finding the maximal errors.

a = -5; b = 5;
x = linspace(a,b,7);            % 7 equidistant nodes
y = 1./(1+x.^2);                % function values at nodes
s = -2*x./(1+x.^2).^2;          % derivatives at nodes

xe = linspace(a,b,1e3);         % evaluation points
ye = 1./(1+xe.^2);              % function values at xe

plot(x,y,'o',xe,ye,'k:')
title('1/(1+x^2)')
hold on

Find piecwise cubic Hermite function, complete spline, not-a-knot spline

The piecewise cubic Hermite function uses function values and derivatives at all nodes.

The complete spline uses function values at the nodes, and the derivative at the first and last node.

The not-a-knot spline uses only the function values at the nodes.

The Hermite function gives the smallest error (it uses the most information about f). The not-a-knot spline performs worse than the complete spline near the endpoints (the complete spline uses the derivatives at the endpoints).

yherm = hermite(x,y,s,xe);      % pw cubic Hermite interpolation
maxerr_herm = max(abs(yherm-ye))

sa = s(1); sb = s(end);         % slopes at left and right endpoint
ycomp = spline(x,[sa,y,sb],xe); % complete spline
maxerr_complete = max(abs(ycomp-ye))

ynak = spline(x,y,xe);          % not-a-knot spline
maxerr_notaknot = max(abs(ynak-ye))

plot(xe,yherm,'b',xe,ycomp,'r',xe,ynak,'g')
legend('given points','f(x)','Hermite','complete spline','not-a-knot spline')
hold off

figure(2)
plot(xe,yherm-ye,'b',xe,ycomp-ye,'r',xe,ynak-ye,'g'); grid on
title('Errors')
legend('Hermite','complete spline','not-a-knot spline')
maxerr_herm =
     0.091289
maxerr_complete =
      0.12884
maxerr_notaknot =
      0.13245