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.optim.univariate;
23
24 import org.hipparchus.analysis.UnivariateFunction;
25 import org.hipparchus.optim.nonlinear.scalar.GoalType;
26 import org.junit.jupiter.api.Test;
27
28 import static org.junit.jupiter.api.Assertions.assertEquals;
29 import static org.junit.jupiter.api.Assertions.assertTrue;
30
31
32
33
34 class BracketFinderTest {
35
36 @Test
37 void testCubicMin() {
38 final BracketFinder bFind = new BracketFinder();
39 final UnivariateFunction func = new UnivariateFunction() {
40 public double value(double x) {
41 if (x < -2) {
42 return value(-2);
43 }
44 else {
45 return (x - 1) * (x + 2) * (x + 3);
46 }
47 }
48 };
49
50 bFind.search(func, GoalType.MINIMIZE, -2 , -1);
51 final double tol = 1e-15;
52
53 assertEquals(-2, bFind.getLo(), tol);
54 assertEquals(-1, bFind.getMid(), tol);
55 assertEquals(0.61803399999999997, bFind.getHi(), tol);
56 }
57
58 @Test
59 void testCubicMax() {
60 final BracketFinder bFind = new BracketFinder();
61 final UnivariateFunction func = new UnivariateFunction() {
62 public double value(double x) {
63 if (x < -2) {
64 return value(-2);
65 }
66 else {
67 return -(x - 1) * (x + 2) * (x + 3);
68 }
69 }
70 };
71
72 bFind.search(func, GoalType.MAXIMIZE, -2 , -1);
73 final double tol = 1e-15;
74 assertEquals(-2, bFind.getLo(), tol);
75 assertEquals(-1, bFind.getMid(), tol);
76 assertEquals(0.61803399999999997, bFind.getHi(), tol);
77 }
78
79 @Test
80 void testMinimumIsOnIntervalBoundary() {
81 final UnivariateFunction func = new UnivariateFunction() {
82 public double value(double x) {
83 return x * x;
84 }
85 };
86
87 final BracketFinder bFind = new BracketFinder();
88
89 bFind.search(func, GoalType.MINIMIZE, 0, 1);
90 assertTrue(bFind.getLo() <= 0);
91 assertTrue(0 <= bFind.getHi());
92
93 bFind.search(func, GoalType.MINIMIZE, -1, 0);
94 assertTrue(bFind.getLo() <= 0);
95 assertTrue(0 <= bFind.getHi());
96 }
97
98 @Test
99 void testIntervalBoundsOrdering() {
100 final UnivariateFunction func = new UnivariateFunction() {
101 public double value(double x) {
102 return x * x;
103 }
104 };
105
106 final BracketFinder bFind = new BracketFinder();
107
108 bFind.search(func, GoalType.MINIMIZE, -1, 1);
109 assertTrue(bFind.getLo() <= 0);
110 assertTrue(0 <= bFind.getHi());
111
112 bFind.search(func, GoalType.MINIMIZE, 1, -1);
113 assertTrue(bFind.getLo() <= 0);
114 assertTrue(0 <= bFind.getHi());
115
116 bFind.search(func, GoalType.MINIMIZE, 1, 2);
117 assertTrue(bFind.getLo() <= 0);
118 assertTrue(0 <= bFind.getHi());
119
120 bFind.search(func, GoalType.MINIMIZE, 2, 1);
121 assertTrue(bFind.getLo() <= 0);
122 assertTrue(0 <= bFind.getHi());
123 }
124 }