Cubic Splines



This page provides the Mathematica Code for finding the cubic spline fit to a set of points that are on the graph of some function f(x) = y. There are a few options to decide upon and the reader/user can choose which option would be appropriate for his or her cubic spline. He or she must decide on the following:


*Should the reader/user decide upon other endpoint conditions, these can easily be incorporated by stating what the second derivatives are at the first endpoint and the last endpoint. Note that the second derivatives at those point are denoted by s[0] and s[n], respectively. The second derivative at the other points are denoted similarly.

The Code


1. First decide whether the cubic spline is that for


Copy and paste the next cell onto the notebook that you will use. You just need to evaluate it.


n=Dimensions[xx][[1]]-1;

i=0;
While[i<=n,
        {x[i]=xx[[i+1]];
         y[i]=yy[[i+1]];
         i=i+1;}];
i=0;
While[i<=n-1,
        {h[i]=x[i+1]-x[i];
         g[i]=(y[i+1]-y[i])/h[i];
         i=i+1;}];

equations=
        Table[h[k-1]*s[k-1]+
                2(h[k-1]+h[k])*s[k]+
                    h[k]*s[k+1]==6(g[k]-g[k-1]),
            {k,1,n-1}];




Decide whether the cubic spline is going to be a



The Solution


You need to paste the next cell onto the notebook that you will use. You just need to evaluate it. What it does is to solve for the different sets of coefficients for each of the different cubic polynomials defined between each pair of nodes.



soln=Solve[equations,Table[s[k],{k,1,n-1}]][[1]]

Clear[a,b,c,d]
i=0;
While[i<=n-1,
      {a[i]=(s[i+1]-s[i])/(6*h[i])/.soln;
       b[i]=s[i]/2/.soln;
       c[i]=(y[i+1]-y[i])/h[i]-(2*h[i]*s[i]+h[i]*s[i+1])/6/.soln;
       d[i]=y[i];
       Print[i];        
       Print[{a[i],b[i],c[i],d[i]}];
       Print[" "];
       i=i+1;}]



The Plots


If you want to see the plots as well, choose from the two options:


Back to the previous page