Calculating derivatives of functions created using SplineFit

SplineFit creates a parametric representation of a function which can be differentiated using the function Interpolation.

Using SplineFit

First we load the package.

<< NumericalMath`SplineFit`

Next we define some points.

points = {{0, 0}, {1, 2}, {-1, 3}, {0, 1}, {3, 0}};

Next we use SplineFit to create a function passing through the points in the order given.

spline = SplineFit[points, Cubic]

Looking at our function

You can see the function does what we want using ParametricPlot.

ParametricPlot[spline[t], {t, 0, 4}, 
      Epilog  ->  {AbsolutePointSize[6], Point /@ points}, 
      Compiled  ->  False]

Building a derivative

To create the derivative of our  function we first create a list of points using the Table function and then Transpose the list to obtain a set of first coordinates and list of second coordinates.

pts  =  Transpose[Table[spline[t], {t, 0, 4,  .02}]];

Next we create a function f1 for x and a second function f2 for y using Interpolation.

f1  =  Interpolation[pts[[1]]]

f2  =  Interpolation[pts[[2]]]

Checking our function

We can quickly see that our functions are doing the right thing using ParametricPlot.

ParametricPlot[{f1[t], f2[t]}, {t, 1, 201}, 
      Epilog  ->  {AbsolutePointSize[6], Point /@ points}]

This gives a slightly strange parameterization of the function since t is assumed to take on the values 1, 2, 3, etc.

Ah the chain rule

We can use the functions f1 and f2 and the chain rule to create the derivative of our spline function.

fprime[t_] =  D[f2[t], t]/D[f1[t], t]

Checking the derivative

We can check the results of our efforts using Plot. The resulting plot is consistent with the behavior of the original function with two vertical tangents and single point with horizontal tangent.

Plot[fprime[t], {t, 1, 201}]

Plotting tangent lines to the curve

To plot tangent lines to the original curve the easiest approach is to define the line in parametric-form. We will plot the tangent line at the point where t = 46.

sol  =  
      Solve[((aa  -  f2[46])/(f1[t]  -  f1[46])) == fprime[46], 
        aa]

linefunc[t_]  =  {f1[t], aa} /. sol[[1]]

ParametricPlot[{{f1[t], f2[t]}, linefunc[t]}, {t, 1, 201}, 
      Compiled  ->  False,  
      Epilog  ->  {AbsolutePointSize[5], Point[{f1[46], f2[46]}]}, 
      PlotRange  ->  {0, 3.12}]

Here we solve for the value of t where the derivative is zero and then plot the horizontal tangent line.

sol2  = t /. FindRoot[fprime[t] == 0, {t, 100}]

sol3  =  
      Solve[((aa  -  f2[sol2])/(f1[t]  -  f1[sol2])) == 
          fprime[sol2], aa]

horlinefunc[t_]  =  {f1[t], aa} /. sol3[[1]]

ParametricPlot[{{f1[t], f2[t]}, horlinefunc[t]}, {t, 1, 201}, 
      Compiled  ->  False,  
      Epilog  ->  {AbsolutePointSize[5], Point[{f1[sol2], f2[sol2]}]}, 
      PlotRange  ->  {0, 3.3}]