1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.analysis.function;
18
19 import org.apache.commons.math4.legacy.analysis.UnivariateFunction;
20 import org.apache.commons.math4.legacy.analysis.differentiation.DerivativeStructure;
21 import org.apache.commons.math4.legacy.analysis.differentiation.UnivariateDifferentiableFunction;
22 import org.apache.commons.math4.core.jdkmath.JdkMath;
23 import org.junit.Assert;
24 import org.junit.Test;
25
26 public class SqrtTest {
27 @Test
28 public void testComparison() {
29 final Sqrt s = new Sqrt();
30 final UnivariateFunction f = new UnivariateFunction() {
31 @Override
32 public double value(double x) {
33 return JdkMath.sqrt(x);
34 }
35 };
36
37 for (double x = 1e-30; x < 1e10; x *= 2) {
38 final double fX = f.value(x);
39 final double sX = s.value(x);
40 Assert.assertEquals("x=" + x, fX, sX, 0);
41 }
42 }
43
44 @Test
45 public void testDerivativeComparison() {
46 final UnivariateDifferentiableFunction sPrime = new Sqrt();
47 final UnivariateFunction f = new UnivariateFunction() {
48 @Override
49 public double value(double x) {
50 return 1 / (2 * JdkMath.sqrt(x));
51 }
52 };
53
54 for (double x = 1e-30; x < 1e10; x *= 2) {
55 final double fX = f.value(x);
56 final double sX = sPrime.value(new DerivativeStructure(1, 1, 0, x)).getPartialDerivative(1);
57 Assert.assertEquals("x=" + x, fX, sX, JdkMath.ulp(fX));
58 }
59 }
60
61 @Test
62 public void testDerivativesHighOrder() {
63 DerivativeStructure s = new Sqrt().value(new DerivativeStructure(1, 5, 0, 1.2));
64 Assert.assertEquals(1.0954451150103322269, s.getPartialDerivative(0), 1.0e-16);
65 Assert.assertEquals(0.45643546458763842789, s.getPartialDerivative(1), 1.0e-16);
66 Assert.assertEquals(-0.1901814435781826783, s.getPartialDerivative(2), 1.0e-16);
67 Assert.assertEquals(0.23772680447272834785, s.getPartialDerivative(3), 1.0e-16);
68 Assert.assertEquals(-0.49526417598485072465, s.getPartialDerivative(4), 1.0e-16);
69 Assert.assertEquals(1.4445205132891479465, s.getPartialDerivative(5), 5.0e-16);
70 }
71 }