GradientFunction implements MultivariateVectorFunction { public double[] value(double[] point) { final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; for (int i = 0; i < point.length; ++i) { dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]); } final DerivativeStructure dsY = f.value(dsX); final double[] y = new double[point.length]; final int[] orders = new int[point.length]; for (int i = 0; i < point.length; ++i) { orders[i] = 1; y[i] = dsY.getPartialDerivative(orders); orders[i] = 0; } return y; } GradientFunction(final MultivariateDifferentiableFunction f); double[] value(double[] point);  }
@Test public void test2DDistance() { EuclideanDistance f = new EuclideanDistance(); GradientFunction g = new GradientFunction(f); for (double x = -10; x < 10; x += 0.5) { for (double y = -10; y < 10; y += 0.5) { double[] point = new double[] { x, y }; TestUtils.assertEquals(f.gradient(point), g.value(point), 1.0e-15); } } }
@Test public void test3DDistance() { EuclideanDistance f = new EuclideanDistance(); GradientFunction g = new GradientFunction(f); for (double x = -10; x < 10; x += 0.5) { for (double y = -10; y < 10; y += 0.5) { for (double z = -10; z < 10; z += 0.5) { double[] point = new double[] { x, y, z }; TestUtils.assertEquals(f.gradient(point), g.value(point), 1.0e-15); } } } }