Search code examples
javaapacheapache-commonsderivativedifferentiation

How to get derivatives using apache lib


I am using apache library to compute derivates. what I want to do is to get the derivates of the following equation

2+(2*x^2)+(3*x)+5

I followed the below posted code but I am a bit confused regarding the parameters stated below. Please help me to find out how to get the derivatives of the above equation.

code:

int params = 1;
int order = 2;
double xRealValue = 5;
DerivativeStructure x = new DerivativeStructure(params, order, 0,  
    xRealValue);
DerivativeStructure y = x.pow(2);                    //COMPILE ERROR
Log.i(TAG, "y = " + y.getValue());
Log.i(TAG, "y = " + y.getPartialDerivative(1));
Log.i(TAG, "y = " + y.getPartialDerivative(2));

Solution

  • commons-math3 version 3.6 does not give any compilation error, and your code works.

    import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
    

    your equation can be written as below

    int xValue = 5;
    
    int howManyUnknowParamsHasFunction = 1;
    int howManyDeriviationWillYouTake = 2;
    int whatIsTheIndexOfThisParameterX = 0;
    
    DerivativeStructure x = new DerivativeStructure(howManyUnknowParamsHasFunction, howManyDeriviationWillYouTake, whatIsTheIndexOfThisParameterX, xValue);
    
    // x --> x^2.
    DerivativeStructure x2 = x.pow(2);
    
    //y = 2x^2 + 3x + 7
    DerivativeStructure y = new DerivativeStructure(2.0, x2, 3.0, x).add(7);