3 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Reid Priedhorsky, Brian Gough
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 /* brent.c -- brent root finding algorithm */
30 #include <gsl/gsl_math.h>
31 #include <gsl/gsl_errno.h>
32 #include <gsl/gsl_roots.h>
44 static int brent_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper);
45 static int brent_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper);
49 brent_init (void * vstate, gsl_function * f, double * root, double x_lower, double x_upper)
51 brent_state_t * state = (brent_state_t *) vstate;
53 double f_lower, f_upper ;
55 *root = 0.5 * (x_lower + x_upper) ;
57 SAFE_FUNC_CALL (f, x_lower, &f_lower);
58 SAFE_FUNC_CALL (f, x_upper, &f_upper);
69 state->d = x_upper - x_lower ;
70 state->e = x_upper - x_lower ;
72 if ((f_lower < 0.0 && f_upper < 0.0) || (f_lower > 0.0 && f_upper > 0.0))
74 GSL_ERROR ("endpoints do not straddle y=0", GSL_EINVAL);
82 brent_iterate (void * vstate, gsl_function * f, double * root, double * x_lower, double * x_upper)
84 brent_state_t * state = (brent_state_t *) vstate;
90 double a = state->a, b = state->b, c = state->c;
91 double fa = state->fa, fb = state->fb, fc = state->fc;
92 double d = state->d, e = state->e;
94 if ((fb < 0 && fc < 0) || (fb > 0 && fc > 0))
103 if (fabs (fc) < fabs (fb))
114 tol = 0.5 * GSL_DBL_EPSILON * fabs (b);
144 if (fabs (e) < tol || fabs (fa) <= fabs (fb))
146 d = m; /* use bisection */
151 double p, q, r; /* use inverse cubic interpolation */
163 p = s * (2 * m * q * (q - r) - (b - a) * (r - 1));
164 q = (q - 1) * (r - 1) * (s - 1);
176 if (2 * p < GSL_MIN (3 * m * q - fabs (tol * q), fabs (e * q)))
183 /* interpolation failed, fall back to bisection */
199 b += (m > 0 ? +tol : -tol);
202 SAFE_FUNC_CALL (f, b, &fb);
213 /* Update the best estimate of the root and bounds on each
218 if ((fb < 0 && fc < 0) || (fb > 0 && fc > 0))
238 static const gsl_root_fsolver_type brent_type =
240 sizeof (brent_state_t),
244 const gsl_root_fsolver_type * gsl_root_fsolver_brent = &brent_type;