main content

cubic spline interpolation -凯发k8网页登录

this example shows how to use the csapi and csape commands from curve fitting toolbox™ to construct cubic spline interpolants.

the csapi command

the command

values = csapi(x,y,xx)

returns the values at xx of the cubic spline interpolant to the given data (x,y), using the not-a-knot end condition. this interpolant is a piecewise cubic function, with break sequence x, whose cubic pieces join together to form a function with two continuous derivatives. the "not-a-knot" end condition means that, at the first and last interior break, even the third derivative is continuous (up to round-off error).

specifying only two data points results in a straight line interpolant.

x = [0 1];
y = [2 0];
xx = linspace(0,6,121);
plot(xx,csapi(x,y,xx),'k-',x,y,'ro')
title('interpolant to two points')

figure contains an axes object. the axes object with title interpolant to two points contains 2 objects of type line. one or more of the lines displays its values using only markers

specifying three data points gives a parabola.

x = [2 3 5];
y = [1 0 4];
plot(xx,csapi(x,y,xx),'k-',x,y,'ro')
title('interpolant to three points')

figure contains an axes object. the axes object with title interpolant to three points contains 2 objects of type line. one or more of the lines displays its values using only markers

more generally, four or more data points give a cubic spline.

x = [1 1.5 2 4.1 5];
y = [1 -1 1 -1 1];
plot(xx,csapi(x,y,xx),'k-',x,y,'ro')
title('cubic spline interpolant to five points')

figure contains an axes object. the axes object with title cubic spline interpolant to five points contains 2 objects of type line. one or more of the lines displays its values using only markers

how to check the output of csapi

these look like nice interpolants, but how do we check that csapi performs as advertised?

we already saw that csapi interpolates, because we plotted the data points and the interpolant went right through those points. but to be sure that we get a cubic spline, it is best to start with data from a cubic spline of the expected sort and check whether csapi reproduces that cubic spline, i.e., gives back that cubic spline from which the data were taken.

example: the truncated power function

one simple example of a cubic spline function to check against is the truncated third power, i.e., the function

f(x)=((x-xi) )3,

where xi is one of the breaks and the " " subscript indicates the truncation function, provided by the command subplus:

help subplus
 subplus positive part.
 
                                   x , if  x>=0
    y  = subplus(x) := (x)_{ }  =               ,
                                   0 , if  x<=0
 
   returns the positive part of x. used for computing truncated powers.

the truncated 3rd power is plotted below for the particular choice xi = 2. as expected, it is zero to the left of 2, and rises like (x-2)^3 to the right of 2.

plot(xx, subplus(xx-2).^3,'y','linewidth',3)
axis([0,6,-10,70])

figure contains an axes object. the axes object contains an object of type line.

now we interpolate this particular cubic spline at the data sites 0:6, and plot the interpolant on top of the spline, in black.

x = 0:6;
y = subplus(x-2).^3;
values = csapi(x,y,xx);
hold on
plot(xx,values,'k',x,y,'ro')
hold off
title('interpolant to ((x-2)_ )^3')

figure contains an axes object. the axes object with title interpolant to ( ( x - 2 ) indexof   baseline ) cubed baseline contains 3 objects of type line. one or more of the lines displays its values using only markers

the interpolation error

when comparing two functions, it is usually much more informative to plot their difference.

plot(xx, values - subplus(xx-2).^3)
title('error in cubic spline interpolation to ((x-2)_ )^3')

figure contains an axes object. the axes object with title error in cubic spline interpolation to ( ( x - 2 ) indexof   baseline ) cubed baseline contains an object of type line.

to put the size of their difference into context, you can also compute the maximum data value. this shows the error to be no worse than the inevitable round-off error.

max_y = max(abs(y))
max_y = 64

a truncated power that cannot be reproduced

as a further test, we interpolate a truncated power whose csapi-produced interpolant at the sites 0:6 cannot coincide with it. for example, the first interior break of the interpolating spline is not really a knot since csapi uses the "not-a-knot" condition, hence the interpolant has three continuous derivatives at that site. this implies that we should not be able to reproduce the truncated 3rd power centered at that site since its third derivative is discontinuous across that site.

values = csapi(x,subplus(x-1).^3,xx);
plot(xx, values - subplus(xx-1).^3)
title('error in not-a-knot interpolant to ((x-1)_ )^3')

figure contains an axes object. the axes object with title error in n o t - a - k n o t blank i n t e r p o l a n t blank t o blank ( ( x - 1 ) indexof   baseline ) cubed baseline contains an object of type line.

since 1 is a first interior knot, it is not active for this interpolant.

the difference is as large as .18, but decays rapidly as we move away from 1. this illustrates that cubic spline interpolation is essentially local.

using the ppform instead of values

it is possible to retain the interpolating cubic spline in a form suitable for subsequent evaluation, or for calculating its derivatives, or for other manipulations. this is done by calling csapi in the form

pp = csapi(x,y)

which returns the ppform of the interpolant. you can evaluate this form at some new points xx by the command

values = fnval(pp,xx)

you can differentiate the interpolant by the command

dpp = fnder(pp)

or integrate it by the command

ipp = fnint(pp)

which return the ppform of the derivative or the integral, respectively.

example: differentiating and integrating the interpolant

to show differentiation of an interpolant, we plot the derivative of this truncated power

f2(x)=3((x-2) )2,

(again in yellow) and then, on top of it, the derivative of our interpolant to the original truncated third power function (again in black).

plot(xx,3*subplus(xx-2).^2,'y','linewidth',3)
pp = csapi(x,subplus(x-2).^3);
dpp = fnder(pp);
hold on
plot(xx,fnval(dpp,xx),'k')
hold off
title('derivative of interpolant to ((x-2)_ )^3')

figure contains an axes object. the axes object with title derivative of interpolant to ( ( x - 2 ) indexof   baseline ) cubed baseline contains 2 objects of type line.

again, the more informative comparison is to plot their difference, and as before this is no bigger than the round-off error.

plot(xx, fnval(dpp,xx) - 3*subplus(xx-2).^2)
title('error in derivative of interpolant to ((x-2)_ )^3')

figure contains an axes object. the axes object with title error in derivative of interpolant to ( ( x - 2 ) indexof   baseline ) cubed baseline contains an object of type line.

the second derivative of the truncated power is

f2(x)=6(x-2)

a plot of the difference between this function and the second derivative of the interpolant to the original function shows that there are now jumps, but they are still within the round-off error.

ddpp = fnder(dpp);
plot(xx, fnval(ddpp,xx) - 6*subplus(xx-2))
title('error in second derivative of interpolant to ((x-2)_ )^3')

figure contains an axes object. the axes object with title error in second derivative of interpolant to ( ( x - 2 ) indexof   baseline ) cubed baseline contains an object of type line.

the integral of the truncated power is

f2(x)=((x-2) )4/4.

a plot of the difference between this function and the integral of the interpolant to the original function again shows that the errors are within the round-off error.

ipp = fnint(pp);
plot(xx, fnval(ipp,xx) - subplus(xx-2).^4/4)
title('error in integral of interpolant to ((x-2)_ )^3')

figure contains an axes object. the axes object with title error in integral of interpolant to ( ( x - 2 ) indexof   baseline ) cubed baseline contains an object of type line.

the csape command

like csapi, the csape command provides a cubic spline interpolant to given data. however, it permits various additional end conditions. its simplest version,

pp = csape(x,y)

uses the lagrange end condition, which is a common alternative to the not-a-knot condition used by csapi. csape does not directly return values of the interpolant, but only its ppform.

for example, consider again interpolation to the function

f1(x)=((x-1) )3,

which csapi fails to reproduce well. we plot the error of the not-a-knot interpolant returned by csapi (in black), along with the error of the interpolant obtained from csape (in red).

exact = subplus(xx-1).^3;
plot(xx, fnval(csapi(x,subplus(x-1).^3),xx) - exact,'k')
hold on
plot(xx, fnval(csape(x,subplus(x-1).^3),xx) - exact,'r')
title('error in not-a-knot vs. lagrange end conditions')
legend({'not-a-knot' 'lagrange'});
hold off

figure contains an axes object. the axes object with title error in not-a-knot vs. lagrange end conditions contains 2 objects of type line. these objects represent not-a-knot, lagrange.

there is not much difference between the two interpolants in this case.

other end conditions: the 'natural' spline interpolant

the csape command also provides ways to specify several other types of end conditions for an interpolating cubic spline. for example, the command

pp = csape(x,y,'variational')

uses the so-called 'natural' end conditions. this means that the second derivative is zero at the two extreme breaks.

this step shows how to apply 'natural' cubic spline interpolation to the function

f2(x)=((x-2) )3,

and plot the error. the code below computes the 'natural' spline interpolant with an alternative argument syntax that is equivalent to the 'variational' argument: using 'second' specifies that csape should set the second derivative at the extreme data sites to the default value of 0.

pp = csape(x,subplus(x-2).^3,'second');
plot(xx, fnval(pp,xx) - subplus(xx-2).^3)
title('error in ''natural'' spline interpolation to ((x-2)_ )^3')

figure contains an axes object. the axes object with title error in ' n a t u r a l ' blank s p l i n e blank i n t e r p o l a t i o n blank t o blank ( ( x - 2 ) indexof   baseline ) cubed baseline contains an object of type line.

note the large error near the right end. this is due to the fact that the 'natural' end conditions implicitly insist on having a zero second derivative there.

other end conditions: prescribing second derivatives

we can also explicitly use the correct second derivatives to get a small error. first, we compute the correct second derivative values of the truncated power at the endpoints.

endcond = 6*subplus(x([1 end])-2);

then we create the interpolant, specifying that second derivatives at the endpoints are to be matched to the second derivative values we just computed. we do this by providing endcond(1) for the left endpoint condition, and endcond(2) for the right, along with the data values.

pp = csape(x,[endcond(1) subplus(x-2).^3 endcond(2)], 'second');
plot(xx, fnval(pp,xx) - subplus(xx-2).^3,'r')
title(['error in spline interpolation to ((x-1)_ )^3'; ...
       '  when matching the 2nd derivative at ends  '])

figure contains an axes object. the axes object with title error in spline interpolation to ( ( x - 1 ) indexof   baseline ) cubed baseline when matching the 2nd derivative at ends contains an object of type line.

other end conditions: prescribing slopes

csape also permits specification of endpoint slopes. this is the clamped (or, complete) cubic spline interpolant. the statement

pp = csape(x,[sl,y,sr],'clamped')

creates the cubic spline interpolant to the data (x, y) that also has slope sl at the leftmost data site and slope sr at the rightmost data site.

other end conditions: mixed end conditions

it is even possible to mix these conditions. for example, our much-exercised truncated power function

f1(x)=((x-1) )3

has slope 0 at x=0 and second derivative 30 at x=6 (the last data site).

therefore, by matching the slope at the left end and the curvature at the right, we expect no error in the resulting interpolant.

pp = csape(x, [0 subplus(x-1).^3 30], [1 2]);
plot(xx, fnval(pp,xx) - subplus(xx-1).^3)
title(['error in spline interpolation to ((x-1)_ )^3'; ...
       '        with mixed end conditions.          '])

figure contains an axes object. the axes object with title error in spline interpolation to ( ( x - 1 ) indexof   baseline ) cubed baseline blank blank blank blank blank blank blank blank blank w i t h blank m i x e d blank e n d blank c o n d i t i o n s . contains an object of type line.

other end conditions: periodic conditions

it is also possible to prescribe periodic end conditions. for example, the sine function is 2*pi-periodic and has the values [0 -1 0 1 0] at the sites (pi/2)*(-2:2). the difference, between the sine function and its periodic cubic spline interpolant at these sites, is only 2 percent. not bad.

x = (pi/2)*(-2:2);
y = [0 -1 0 1 0];
pp = csape(x,y, 'periodic' );
xx = linspace(-pi,pi,201);
plot(xx, sin(xx) - fnval(pp,xx), 'x')
title('error in periodic cubic spline interpolation to sin(x)')

figure contains an axes object. the axes object with title error in periodic cubic spline interpolation to sin(x) contains a line object which displays its values using only markers.

end conditions not explicitly covered by csapi or csape

any end condition not covered explicitly by csapi or csape can be handled by constructing the interpolant with the csape default side conditions, and then adding to it an appropriate scalar multiple of an interpolant to zero values and some side conditions. if there are two `nonstandard' side conditions to be satisfied, you may have to solve a 2-by-2 linear system first.

for example, suppose that you want to compute the cubic spline interpolant s to the data

x = 0:.25:3;
q = @(x) x.*(-1   x.*(-1 x.*x/5));
y = q(x);

and enforce the condition

lambda(s) := a * (ds)(e) b * (d^2 s)(e) = c

on the first and second derivatives of s at the point e.

the data were generated from a quartic polynomial that happens to satisfy this side condition with specific parameters

e = x(1);
a = 2; b = -3; c = 4;

to construct the interpolant that satisfies this specific condition, we first construct the interpolant with the default end conditions

pp1 = csape(x,y);

and the first derivative of its first polynomial piece.

dp1 = fnder(fnbrk(pp1,1));

in addition, we construct the cubic spline interpolant to zero data values, specifying that it have a slope of 1 at e,

pp0 = csape(x,[1,zeros(size(y)),0], [1,0]);

as well as constructing the first derivative of its first polynomial piece.

dp0 = fnder(fnbrk(pp0,1));

then we compute lambda for both pp1 and pp0,

lam1 = a*fnval(dp1,e)   b*fnval(fnder(dp1),e);
lam0 = a*fnval(dp0,e)   b*fnval(fnder(dp0),e);

and construct the correct linear combination of pp1 and pp0 to get a cubic spline

s := pp1 ((c - lambda(pp1))/lambda(pp0)) * pp0

that does satisfy the desired condition, as well as the default end condition at the right endpoint. we form this linear combination with the help of fncmb.

s = fncmb(pp0,(c-lam1)/lam0,pp1);

a plot of the interpolation error shows that s fits the quartic polynomial slightly better near e than the interpolant pp1 with the default conditions does.

xx = (-.3):.05:.7; yy = q(xx);
plot(xx, fnval(pp1,xx) - yy, 'x')
hold on
plot(xx, fnval(s,xx) - yy, 'o')
hold off
legend({'default conditions' 'nonstandard conditions'},'location','se')

figure contains an axes object. the axes object contains 2 objects of type line. one or more of the lines displays its values using only markers these objects represent default conditions, nonstandard conditions.

if we want to enforce the condition

mu(s) := (d^3 s)(3) = 14.6

on the third derivative of the interpolant (the quartic satisfies this condition), then we construct an additional cubic spline interpolating to zero values, and with zero first derivative at the left endpoint, hence certain to be independent from pp0.

pp2 = csape(x,[0,zeros(size(y)),1],[0,1]);

then we find the coefficients d0 and d2 in the linear combination

s := pp1 d0*pp0 d2*pp2

that solves the linear system

lambda(s) = c

mu(s) = 14.6

note that both pp0 and pp2 vanish at all interpolation sites, hence s will match the given data for any choice of d0 and d2.

for amusement, we use the matlab® encoding facility to write a loop to compute lambda(pp_j) and mu(pp_j), for j=0:2.

dd = zeros(2,3);
for j=0:2
   j = num2str(j);
   eval(['dpp',j,'=fnder(pp',j,');']);
   eval(['ddpp',j,'=fnder(dpp',j,');']);
   eval(['dd(1,1 ',j,')=a*fnval(dpp',j,',e) b*fnval(ddpp',j,',e);']);
   eval(['dd(2,1 ',j,')=fnval(fnder(ddpp',j,'),3);']);
end

given the values of lambda and mu for pp0, pp1, and pp2, we then solve for the coefficients that define the correct linear combination.

d = dd(:,[1,3])\([c;14.6]-dd(:,2));
s = fncmb(fncmb(pp0,d(1),pp2,d(2)),pp1);
xxx = 0:.05:3;
yyy = q(xxx);
plot(xxx, yyy - fnval(s,xxx),'x')
title('error in spline interpolant to y = x*(-1   x*(-1 x*x/5))')

figure contains an axes object. the axes object with title error in spline interpolant to y = x*(-1   x*(-1 x*x/5)) contains a line object which displays its values using only markers.

for reassurance, we compare this error with the one obtained in complete cubic spline interpolation to this function:

hold on
plot(xxx, yyy - fnval(csape(x,[-1,y,-7 (4/5)*27],'clamped'),xxx),'o')
hold off
legend({'nonstandard conditions' 'endslope conditions'})

figure contains an axes object. the axes object with title error in spline interpolant to y = x*(-1   x*(-1 x*x/5)) contains 2 objects of type line. one or more of the lines displays its values using only markers these objects represent nonstandard conditions, endslope conditions.

the errors differ (and not by much) only near the end points, testifying to the fact that both pp0 and pp2 are sizable only near their respective end points.

as a final check, we verify that s satisfies the desired third derivative condition at 3.

fnval(fnder(s,3),3)
ans = 14.6000
网站地图