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