Search code examples
javanumerical-methodsapache-commons-math

Interpolation and derivative on Java


I am trying to make a project witch involves calculating an interpolation from raw data and its derivative. I have two arrays looking like this:

A = { 1, 2, 3, 4, ... , n }
B = { 0.23, 0.43, 0.24, 0.19, ... , n }

I want a function to describe the following arrays, so I am using apache-common-math library in order to interpolate the polynom that will describe a function where: F(A[i]) = B[i]. Afterwards, I wish to calculate the derivative of this function in order to be able to find extremum(max/min).

For some reason, I am having trouble with the derivative part.

Currently using:

        DividedDifferenceInterpolator devider = new DividedDifferenceInterpolator();
        PolynomialFunctionNewtonForm polynom = devider.interpolate(xArray,  
        yArray);

Now i have polynom, which is the function representing my previous arrays. How should I calculate its derivative..?

Thanks.


Solution

  • You can get the derivative by extracting the coefficients from the Newton form polynomial, creating a PolynomialFunction from it and then using that function's derivative method. Here is an example:

    double[] x = {0, 1, 2, 3, 4, 5};
    double[] y = new double[6];
    for (int i = 0; i < 6; i++) {
        y[i] = 1 + 2 * x[i] + 3 * x[i] * x[i];
    }
    DividedDifferenceInterpolator divider = new DividedDifferenceInterpolator();
    PolynomialFunctionNewtonForm polynom = divider.interpolate(x, y);
    double[] coefficients = polynom.getCoefficients();
    System.out.println(Arrays.toString(coefficients));
    PolynomialFunction derivative =
     (PolynomialFunction) new PolynomialFunction(coefficients).derivative();
    System.out.println(Arrays.toString(derivative.getCoefficients()));
    

    The code above generates points from the polynomial y = 1 + 2x + 3x^2. The output should be

    [1.0, 2.0, 3.0, 0.0, 0.0, 0.0]
    [2.0, 6.0]