Usama
Usama

Reputation: 11

Finding the derivaitive of a spline function in Java

I am currently finding the cubic spline of raw data:

    double y[] = { 0.0, 1.0, 2.0,3.0,4.0,5.0 };
    double x[] = { 0.0, 1.0, 8.0, 27.0, 64, 125};
    //these arrays are just an example

    UnivariateInterpolator interpolator = new SplineInterpolator();
    UnivariateFunction spline = interpolator.interpolate(y, x);
    double interpolatedY = spline.value(5.0);

And I am using interpolatedY variable in another part of my program. I also need to find the derivative of the UnivariateFuction spline such that I can compute y'(x) where x can be any value. I have tried using the method below:

  // function to be differentiated
    UnivariateFunction basicF = new UnivariateFunction() {
                                    public double value(double x) {
                                        return spline.value(x);
                                    }
                                };

// create a differentiator using 5 points and 0.01 step
 FiniteDifferencesDifferentiator differentiator =
         new FiniteDifferencesDifferentiator(51, 0.01);

 UnivariateDifferentiableFunction completeF = differentiator.differentiate(basicF);

System.out.println("y'(x=2) = " + completeF.value(new DerivativeStructure(1,1,0,2).getPartialDerivative(1)));

But this looks a but long-winded and it doesn't return the right answer. Any suggestions?

Thanks

Upvotes: 1

Views: 375

Answers (1)

StaticBeagle
StaticBeagle

Reputation: 5175

interpolator.interpolate(y, x) returns a PolynomialSplineFunction that extends the following interfaces:

  1. DifferentiableUnivariateFunction (deprecated)
  2. UnivariateDifferentiableFunction
  3. UnivariateFunction

One thing you can do is, instead of using UnivariateFunction and UnivariateInterpolator, you can use UnivariateDifferentiableFunction and SplineInterpolator as follows:

SplineInterpolator interpolator = new SplineInterpolator();
UnivariateDifferentiableFunction spline = interpolator.interpolate(y, x);
double interpolatedY = spline.value(5.0);

DerivativeStructure ds = spline.value(new DerivativeStructure(1, 1, 0, 2));
System.out.println(ds.getPartialDerivative(1));

Output

// Function to interpolate f(x) = x^3
// First order derivative  f'(x) = 3x^2
// f'(2) = 12.0
Approximation: 12.167464114832537
Theoretical:   12.0

Notes

Internally, the spline interpolator computes the Natural Cubic Spline. The Natural Cubic Spline for your x and y is enter image description here
Since you are trying to evaluate the first derivative at 2.0, the function of interest is:

f(x) = 1.1196 x^3 - 0.43062 x^2 + 0.45455 x - 0.14354  

Taking the first derivative:

f'(x) = 3.3588 x^2 - 0.8612 x + 0.4546

Now plugging 2 into f'(x)

f'(2) = 12.1674

Which corroborates the results we obtained previously.

Upvotes: 1

Related Questions