View Javadoc

1   /*
2    * Copyright 2003-2004 The Apache Software Foundation.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.commons.math.analysis;
17  
18  
19  import org.apache.commons.math.ConvergenceException;
20  import org.apache.commons.math.FunctionEvaluationException;
21  
22  /***
23   * Implements the <a href="http://mathworld.wolfram.com/BrentsMethod.html">
24   * Brent algorithm</a> for  finding zeros of real univariate functions.
25   * <p>
26   * The function should be continuous but not necessarily smooth.
27   *  
28   * @version $Revision: 1.18 $ $Date: 2004/11/07 02:17:56 $
29   */
30  public class BrentSolver extends UnivariateRealSolverImpl {
31      
32      /*** Serializable version identifier */
33      static final long serialVersionUID = 3350616277306882875L;
34  
35      /***
36       * Construct a solver for the given function.
37       * 
38       * @param f function to solve.
39       */
40      public BrentSolver(UnivariateRealFunction f) {
41          super(f, 100, 1E-6);
42      }
43  
44      /***
45       * Find a zero in the given interval.
46       * <p>
47       * Throws <code>ConvergenceException</code> if the values of the function
48       * at the endpoints of the interval have the same sign.
49       * 
50       * @param min the lower bound for the interval.
51       * @param max the upper bound for the interval.
52       * @param initial the start value to use (ignored).
53       * @return the value where the function is zero
54       * @throws ConvergenceException the maximum iteration count is exceeded 
55       * @throws FunctionEvaluationException if an error occurs evaluating
56       *  the function
57       * @throws IllegalArgumentException if initial is not between min and max
58       */
59      public double solve(double min, double max, double initial)
60          throws ConvergenceException, FunctionEvaluationException {
61              
62          return solve(min, max);
63      }
64      
65      /***
66       * Find a zero in the given interval.
67       * <p>
68       * Requires that the values of the function at the endpoints have opposite
69       * signs. An <code>IllegalArgumentException</code> is thrown if this is not
70       * the case.
71       * 
72       * @param min the lower bound for the interval.
73       * @param max the upper bound for the interval.
74       * @return the value where the function is zero
75       * @throws ConvergenceException if the maximum iteration count is exceeded
76       * @throws FunctionEvaluationException if an error occurs evaluating the
77       * function 
78       * @throws IllegalArgumentException if min is not less than max or the
79       * signs of the values of the function at the endpoints are not opposites
80       */
81      public double solve(double min, double max) throws ConvergenceException, 
82          FunctionEvaluationException {
83          
84          clearResult();
85          verifyBracketing(min, max, f);
86          
87          // Index 0 is the old approximation for the root.
88          // Index 1 is the last calculated approximation  for the root.
89          // Index 2 is a bracket for the root with respect to x1.
90          double x0 = min;
91          double x1 = max;
92          double y0;
93          double y1;
94          y0 = f.value(x0);
95          y1 = f.value(x1);
96     
97          double x2 = x0;
98          double y2 = y0;
99          double delta = x1 - x0;
100         double oldDelta = delta;
101 
102         int i = 0;
103         while (i < maximalIterationCount) {
104             if (Math.abs(y2) < Math.abs(y1)) {
105                 x0 = x1;
106                 x1 = x2;
107                 x2 = x0;
108                 y0 = y1;
109                 y1 = y2;
110                 y2 = y0;
111             }
112             if (Math.abs(y1) <= functionValueAccuracy) {
113                 // Avoid division by very small values. Assume
114                 // the iteration has converged (the problem may
115                 // still be ill conditioned)
116                 setResult(x1, i);
117                 return result;
118             }
119             double dx = (x2 - x1);
120             double tolerance =
121                 Math.max(relativeAccuracy * Math.abs(x1), absoluteAccuracy);
122             if (Math.abs(dx) <= tolerance) {
123                 setResult(x1, i);
124                 return result;
125             }
126             if ((Math.abs(oldDelta) < tolerance) ||
127                     (Math.abs(y0) <= Math.abs(y1))) {
128                 // Force bisection.
129                 delta = 0.5 * dx;
130                 oldDelta = delta;
131             } else {
132                 double r3 = y1 / y0;
133                 double p;
134                 double p1;
135                 if (x0 == x2) {
136                     // Linear interpolation.
137                     p = dx * r3;
138                     p1 = 1.0 - r3;
139                 } else {
140                     // Inverse quadratic interpolation.
141                     double r1 = y0 / y2;
142                     double r2 = y1 / y2;
143                     p = r3 * (dx * r1 * (r1 - r2) - (x1 - x0) * (r2 - 1.0));
144                     p1 = (r1 - 1.0) * (r2 - 1.0) * (r3 - 1.0);
145                 }
146                 if (p > 0.0) {
147                     p1 = -p1;
148                 } else {
149                     p = -p;
150                 }
151                 if (2.0 * p >= 1.5 * dx * p1 - Math.abs(tolerance * p1) ||
152                         p >= Math.abs(0.5 * oldDelta * p1)) {
153                     // Inverse quadratic interpolation gives a value
154                     // in the wrong direction, or progress is slow.
155                     // Fall back to bisection.
156                     delta = 0.5 * dx;
157                     oldDelta = delta;
158                 } else {
159                     oldDelta = delta;
160                     delta = p / p1;
161                 }
162             }
163             // Save old X1, Y1 
164             x0 = x1;
165             y0 = y1;
166             // Compute new X1, Y1
167             if (Math.abs(delta) > tolerance) {
168                 x1 = x1 + delta;
169             } else if (dx > 0.0) {
170                 x1 = x1 + 0.5 * tolerance;
171             } else if (dx <= 0.0) {
172                 x1 = x1 - 0.5 * tolerance;
173             }
174             y1 = f.value(x1);
175             if ((y1 > 0) == (y2 > 0)) {
176                 x2 = x0;
177                 y2 = y0;
178                 delta = x1 - x0;
179                 oldDelta = delta;
180             }
181             i++;
182         }
183         throw new ConvergenceException("Maximum number of iterations exceeded.");
184     }
185 }