@Test
public void testNumericalGradient() {
// our function is f(x,y) = x^2+y^2
// the derivative is f'(x,y) = 2x+2y
final CostFunction inlineFunction = new CostFunction() {
@Override
public CostGradientTuple evaluateCost(DoubleVector input) {
double cost = Math.pow(input.get(0), 2) + Math.pow(input.get(1), 2);
DenseDoubleVector gradient = new DenseDoubleVector(new double[] {
input.get(0) * 2, input.get(1) * 2 });
return new CostGradientTuple(cost, gradient);
}
};
DenseDoubleVector v = new DenseDoubleVector(new double[] { 0, 1 });
CostGradientTuple cost = inlineFunction.evaluateCost(v);
DoubleVector numericalGradient = MathUtils.numericalGradient(v,
inlineFunction);
assertSmallDiff(numericalGradient, cost.getGradient());
v = new DenseDoubleVector(new double[] { -15, 100 });
cost = inlineFunction.evaluateCost(v);
numericalGradient = MathUtils.numericalGradient(v, inlineFunction);
assertSmallDiff(numericalGradient, cost.getGradient());
}