commons-math differentiation result is 0

134 views Asked by At

I'm trying to use commons-math library for some numerical differentiation task. I've built a very simple function using DerivativeStructures which I thought would work; apparently I was wrong.

public static void main(String[] args) {
    DerivativeStructure x0 = new DerivativeStructure(2, 2, 2.0);
    DerivativeStructure y0 = new DerivativeStructure(2, 2, 4.0);
    DerivativeStructure xi = x0.pow(2);
    DerivativeStructure yi = y0.pow(2);
    DerivativeStructure f = xi.add(yi);

    System.out.println(f.getValue());
    System.out.println(f.getPartialDerivative(1, 0)); // (?)
    System.out.println(f.getPartialDerivative(0, 1)); // (?)
}

I'm trying to get the 1st and 2nd order partial derivatives of a the multivariate function f(x)=x^2+y^2 at point (2.0, 4.0). As a result I'd expect 4.0 for df/dx and 8.0 for df/dy as first order partials. 2.0 for second order partials. I however am getting the correct f(x,y) value and I don't even have the slightest idea from this javadoc. I saw a couple questions here on stackoverflow with some comments about the opaque documentation for commons-math but not a working example on multivariate functions. Univariate I can work out, but not this...

Any tips would be appreciated!

1

There are 1 answers

0
Manos Nikolaidis On BEST ANSWER

In your code you haven't really specified 2 independent variables x0, y0 but only 1. With DerivativeStructure x0, y0 are actually seen as functions themselves depending on an implicit vector of variables p. For each independent variable you have to give a different index into the p vector of independent variables. What you need to do is:

DerivativeStructure x0 = new DerivativeStructure(2, 2, 0, 2.0);
DerivativeStructure y0 = new DerivativeStructure(2, 2, 1, 4.0);

Where the third parameter(s) 0 and 1 indicate 2 different indexes in the p vector therefore two different independent variables. If you omit this parameter when creating a DerivativeStructure, 0 is assumed so in your code x0, y0 are not independent.

Further Reading