View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus.analysis.solvers;
24  
25  import org.hipparchus.analysis.QuinticFunction;
26  import org.hipparchus.analysis.UnivariateFunction;
27  import org.hipparchus.analysis.differentiation.Derivative;
28  import org.hipparchus.analysis.differentiation.UnivariateDifferentiableFunction;
29  import org.hipparchus.exception.MathIllegalArgumentException;
30  import org.hipparchus.exception.MathIllegalStateException;
31  import org.hipparchus.util.FastMath;
32  import org.junit.jupiter.api.Test;
33  
34  import java.util.ArrayList;
35  import java.util.List;
36  
37  import static org.junit.jupiter.api.Assertions.assertEquals;
38  import static org.junit.jupiter.api.Assertions.assertThrows;
39  import static org.junit.jupiter.api.Assertions.assertTrue;
40  
41  /**
42   * Test case for
43   * {@link BracketingNthOrderBrentSolver bracketing n<sup>th</sup> order Brent}
44   * solver.
45   */
46  final class BracketingNthOrderBrentSolverTest extends BaseSecantSolverAbstractTest {
47  
48      /** {@inheritDoc} */
49      @Override
50      protected UnivariateSolver getSolver() {
51          return new BracketingNthOrderBrentSolver();
52      }
53  
54      /** {@inheritDoc} */
55      @Override
56      protected int[] getQuinticEvalCounts() {
57          return new int[] { 1, 3, 8, 1, 9, 4, 8, 1, 12, 1, 16 };
58      }
59  
60      @Test
61      void testInsufficientOrder1() {
62          assertThrows(MathIllegalArgumentException.class, () -> new BracketingNthOrderBrentSolver(1.0e-10, 1));
63      }
64  
65      @Test
66      void testInsufficientOrder2() {
67          assertThrows(MathIllegalArgumentException.class, () -> new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1));
68      }
69  
70      @Test
71      void testInsufficientOrder3() {
72          assertThrows(MathIllegalArgumentException.class, () -> new BracketingNthOrderBrentSolver(1.0e-10, 1.0e-10, 1.0e-10, 1));
73      }
74  
75      @Test
76      void testConstructorsOK() {
77          assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10,
78                                                                       2).getMaximalOrder());
79          assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10,
80                                                                       1.0e-10,
81                                                                       2).getMaximalOrder());
82          assertEquals(2, new BracketingNthOrderBrentSolver(1.0e-10,
83                                                                       1.0e-10,
84                                                                       1.0e-10,
85                                                                       2).getMaximalOrder());
86      }
87  
88      @Test
89      void testConvergenceOnFunctionAccuracy() {
90          BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(
91                          1.0e-12, 1.0e-10, 0.001, 3);
92          QuinticFunction f = new QuinticFunction();
93          double result = solver.solve(20, f, 0.2, 0.9, 0.4,
94                                       AllowedSolution.BELOW_SIDE);
95          assertEquals(0, f.value(result),
96                                  solver.getFunctionValueAccuracy());
97          assertTrue(f.value(result) <= 0);
98          assertTrue(result - 0.5 > solver.getAbsoluteAccuracy());
99          result = solver.solve(20, f, -0.9, -0.2, -0.4,
100                               AllowedSolution.ABOVE_SIDE);
101         assertEquals(0, f.value(result),
102                                 solver.getFunctionValueAccuracy());
103         assertTrue(f.value(result) >= 0);
104         assertTrue(result + 0.5 < -solver.getAbsoluteAccuracy());
105     }
106 
107     @Test
108     void testIssue716() {
109         BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(
110                         1.0e-12, 1.0e-10, 1.0e-22, 5);
111         UnivariateFunction sharpTurn = x -> (2 * x + 1) / (1.0e9 * (x + 1));
112         double result = solver.solve(100, sharpTurn, -0.9999999, 30, 15,
113                                      AllowedSolution.RIGHT_SIDE);
114         assertEquals(0, sharpTurn.value(result),
115                                 solver.getFunctionValueAccuracy());
116         assertTrue(sharpTurn.value(result) >= 0);
117         assertEquals(-0.5, result, 1.0e-10);
118     }
119 
120     @Test
121     void testToleranceLessThanUlp() {
122         // function that is never zero
123         UnivariateFunction f = (x) -> x < 2.1 ? -1 : 1;
124         // tolerance less than 1 ulp(x)
125         UnivariateSolver solver = new BracketingNthOrderBrentSolver(0, 1e-18, 0,
126                                                                     5);
127 
128         // make sure it doesn't throw a maxIterations exception
129         double result = solver.solve(100, f, 0.0, 5.0);
130         assertEquals(2.1, result, 0.0);
131     }
132 
133     @Test
134     void testFasterThanNewton() {
135         // the following test functions come from Beny Neta's paper:
136         // "Several New Methods for solving Equations"
137         // intern J. Computer Math Vol 23 pp 265-282
138         // available here: http://www.math.nps.navy.mil/~bneta/SeveralNewMethods.PDF
139         // the reference roots have been computed by the Dfp solver to more than
140         // 80 digits and checked with emacs (only the first 20 digits are reproduced here)
141         compare(new TestFunction(0.0, -2, 2) {
142 
143             @Override
144             public <T extends Derivative<T>> T value(T x) {
145                 return x.sin().subtract(x.multiply(0.5));
146             }
147         });
148         compare(new TestFunction(6.3087771299726890947, -5, 10) {
149 
150             @Override
151             public <T extends Derivative<T>> T value(T x) {
152                 return x.pow(5).add(x).subtract(10000);
153             }
154         });
155         compare(new TestFunction(9.6335955628326951924, 0.001, 10) {
156 
157             @Override
158             public <T extends Derivative<T>> T value(T x) {
159                 return x.sqrt().subtract(x.reciprocal()).subtract(3);
160             }
161         });
162         compare(new TestFunction(2.8424389537844470678, -5, 5) {
163 
164             @Override
165             public <T extends Derivative<T>> T value(T x) {
166                 return x.exp().add(x).subtract(20);
167             }
168         });
169         compare(new TestFunction(8.3094326942315717953, 0.001, 10) {
170 
171             @Override
172             public <T extends Derivative<T>> T value(T x) {
173                 return x.log().add(x.sqrt()).subtract(5);
174             }
175         });
176         compare(new TestFunction(1.4655712318767680266, -0.5, 1.5) {
177 
178             @Override
179             public <T extends Derivative<T>> T value(T x) {
180                 return x.subtract(1).multiply(x.square()).subtract(1);
181             }
182         });
183 
184     }
185 
186     @Test
187     void testSolverStopIteratingOnceSolutionIsFound() {
188         final double absoluteAccuracy = 0.1;
189         final double valueAccuracy = 1.;
190         BracketingNthOrderBrentSolver solver = new BracketingNthOrderBrentSolver(
191                         1e-14, absoluteAccuracy, valueAccuracy, 5);
192         FunctionHipparcus function = new FunctionHipparcus();
193         solver.solve(100, function, -100, 100);
194         assertEquals(1, function.values.stream()
195                         .filter(value -> FastMath.abs(value) < valueAccuracy)
196                         .count());
197         assertEquals(7, function.values.size());
198     }
199 
200     private static class FunctionHipparcus implements UnivariateFunction {
201 
202         List<Double> values = new ArrayList<>();
203 
204         @Override
205         public double value(double x) {
206             double value = -0.01 * x * x + 20;
207             values.add(value);
208             return value;
209         }
210     }
211 
212     private void compare(TestFunction f) {
213         compare(f, f.getRoot(), f.getMin(), f.getMax());
214     }
215 
216     private void compare(final UnivariateDifferentiableFunction f, double root,
217                          double min, double max) {
218         NewtonRaphsonSolver newton = new NewtonRaphsonSolver(1.0e-12);
219         BracketingNthOrderBrentSolver bracketing = new BracketingNthOrderBrentSolver(
220                         1.0e-12, 1.0e-12, 1.0e-18, 5);
221         double resultN;
222         try {
223             resultN = newton.solve(100, f, min, max);
224         } catch (MathIllegalStateException tmee) {
225             resultN = Double.NaN;
226         }
227         double resultB;
228         try {
229             resultB = bracketing.solve(100, f, min, max);
230         } catch (MathIllegalStateException tmee) {
231             resultB = Double.NaN;
232         }
233         assertEquals(root, resultN, newton.getAbsoluteAccuracy());
234         assertEquals(root, resultB,
235                                 bracketing.getAbsoluteAccuracy());
236 
237         // bracketing solver evaluates only function value, we set the weight to 1
238         final int weightedBracketingEvaluations = bracketing.getEvaluations();
239 
240         // Newton-Raphson solver evaluates both function value and derivative, we set the weight to 2
241         final int weightedNewtonEvaluations = 2 * newton.getEvaluations();
242 
243         assertTrue(
244                         weightedBracketingEvaluations < weightedNewtonEvaluations);
245 
246     }
247 
248     private abstract static class TestFunction implements UnivariateDifferentiableFunction {
249 
250         private final double root;
251 
252         private final double min;
253 
254         private final double max;
255 
256         protected TestFunction(final double root, final double min,
257                                final double max) {
258             this.root = root;
259             this.min = min;
260             this.max = max;
261         }
262 
263         public double getRoot() {
264             return root;
265         }
266 
267         public double getMin() {
268             return min;
269         }
270 
271         public double getMax() {
272             return max;
273         }
274 
275         public abstract <T extends Derivative<T>> T value(final T t);
276 
277     }
278 
279 }