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