1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.analysis.solvers;
18
19 import org.apache.commons.math4.legacy.exception.NoBracketingException;
20 import org.apache.commons.math4.legacy.exception.TooManyEvaluationsException;
21 import org.apache.commons.math4.core.jdkmath.JdkMath;
22
23
24
25
26
27
28
29
30
31
32
33
34 public class RiddersSolver extends AbstractUnivariateSolver {
35
36 private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6;
37
38
39
40
41 public RiddersSolver() {
42 this(DEFAULT_ABSOLUTE_ACCURACY);
43 }
44
45
46
47
48
49 public RiddersSolver(double absoluteAccuracy) {
50 super(absoluteAccuracy);
51 }
52
53
54
55
56
57
58 public RiddersSolver(double relativeAccuracy,
59 double absoluteAccuracy) {
60 super(relativeAccuracy, absoluteAccuracy);
61 }
62
63
64
65
66 @Override
67 protected double doSolve()
68 throws TooManyEvaluationsException,
69 NoBracketingException {
70 double min = getMin();
71 double max = getMax();
72
73
74
75 double x1 = min;
76 double y1 = computeObjectiveValue(x1);
77 double x2 = max;
78 double y2 = computeObjectiveValue(x2);
79
80
81 if (y1 == 0) {
82 return min;
83 }
84 if (y2 == 0) {
85 return max;
86 }
87 verifyBracketing(min, max);
88
89 final double absoluteAccuracy = getAbsoluteAccuracy();
90 final double functionValueAccuracy = getFunctionValueAccuracy();
91 final double relativeAccuracy = getRelativeAccuracy();
92
93 double oldx = Double.POSITIVE_INFINITY;
94 while (true) {
95
96 final double x3 = 0.5 * (x1 + x2);
97 final double y3 = computeObjectiveValue(x3);
98 if (JdkMath.abs(y3) <= functionValueAccuracy) {
99 return x3;
100 }
101 final double delta = 1 - (y1 * y2) / (y3 * y3);
102 final double correction = (JdkMath.signum(y2) * JdkMath.signum(y3)) *
103 (x3 - x1) / JdkMath.sqrt(delta);
104 final double x = x3 - correction;
105 final double y = computeObjectiveValue(x);
106
107
108 final double tolerance = JdkMath.max(relativeAccuracy * JdkMath.abs(x), absoluteAccuracy);
109 if (JdkMath.abs(x - oldx) <= tolerance) {
110 return x;
111 }
112 if (JdkMath.abs(y) <= functionValueAccuracy) {
113 return x;
114 }
115
116
117
118 if (correction > 0.0) {
119 if (JdkMath.signum(y1) + JdkMath.signum(y) == 0.0) {
120 x2 = x;
121 y2 = y;
122 } else {
123 x1 = x;
124 x2 = x3;
125 y1 = y;
126 y2 = y3;
127 }
128 } else {
129 if (JdkMath.signum(y2) + JdkMath.signum(y) == 0.0) {
130 x1 = x;
131 y1 = y;
132 } else {
133 x1 = x3;
134 x2 = x;
135 y1 = y3;
136 y2 = y;
137 }
138 }
139 oldx = x;
140 }
141 }
142 }