Skip to main content

lib_jsl_root_finding/
van_wijngaarden_dekker_brent.rs

1//! Van Wijngaarden-Dekker-Brent method.
2//!
3//! See the book entry [Bracketing methods](https://jwkunz.github.io/lib_jsl/book/root_finding/bracketing.html#brents-method).
4
5use lib_jsl_core::ErrorsJSL;
6use crate::same_sign;
7
8/// Finds a root of `f` in `[a, b]` using Brent's method (inverse quadratic interpolation,
9/// secant and bisection). Requires a sign change over the interval.
10///
11/// Returns when the bracket around the best estimate has half-width below `tol / 2 + 2ε|x|`, so
12/// the root is located to within about `tol`. Converges superlinearly near a simple root. At a
13/// multiple root the interpolation steps converge only linearly, and Brent's safeguard forces a
14/// bisection only every few steps, so it can need several times the evaluations of bisection
15/// (131 against 46 for `(x − 1/3)³` on `[0, 1]`); its guaranteed worst case is about the square
16/// of bisection's count.
17pub fn brent_method<F>(f: F, a: f64, b: f64, tol: f64) -> Result<f64, ErrorsJSL>
18where
19    F: Fn(f64) -> f64,
20{
21    let (mut a, mut b) = (a, b);
22    let (mut fa, mut fb) = (f(a), f(b));
23    if fa == 0.0 {
24        return Ok(a);
25    }
26    if fb == 0.0 {
27        return Ok(b);
28    }
29    if !(fa < 0.0 && fb > 0.0 || fa > 0.0 && fb < 0.0) {
30        return Err(ErrorsJSL::InvalidInputRange("brent_method: f(a) and f(b) must have opposite signs"));
31    }
32    let (mut c, mut fc) = (a, fa);
33    let mut d = b - a;
34    let mut e = d;
35    for _ in 0..200 {
36        if same_sign(fb, fc) {
37            c = a;
38            fc = fa;
39            d = b - a;
40            e = d;
41        }
42        if fc.abs() < fb.abs() {
43            a = b;
44            b = c;
45            c = a;
46            fa = fb;
47            fb = fc;
48            fc = fa;
49        }
50        let tol1 = 2.0 * f64::EPSILON * b.abs() + 0.5 * tol;
51        let xm = 0.5 * (c - b);
52        if xm.abs() <= tol1 || fb == 0.0 {
53            return Ok(b);
54        }
55        // ANCHOR: brent_step
56        if e.abs() >= tol1 && fa.abs() > fb.abs() {
57            let s = fb / fa;
58            let (mut p, mut q);
59            if a == c {
60                p = 2.0 * xm * s;
61                q = 1.0 - s;
62            } else {
63                let qq = fa / fc;
64                let r = fb / fc;
65                p = s * (2.0 * xm * qq * (qq - r) - (b - a) * (r - 1.0));
66                q = (qq - 1.0) * (r - 1.0) * (s - 1.0);
67            }
68            if p > 0.0 {
69                q = -q;
70            }
71            p = p.abs();
72            let min1 = 3.0 * xm * q - (tol1 * q).abs();
73            let min2 = (e * q).abs();
74            if 2.0 * p < min1.min(min2) {
75                e = d;
76                d = p / q;
77            } else {
78                d = xm;
79                e = d;
80            }
81        } else {
82            d = xm;
83            e = d;
84        }
85        // ANCHOR_END: brent_step
86        a = b;
87        fa = fb;
88        if d.abs() > tol1 {
89            b += d;
90        } else {
91            b += if xm >= 0.0 { tol1 } else { -tol1 };
92        }
93        fb = f(b);
94    }
95    Err(ErrorsJSL::RuntimeError("brent_method: failed to converge"))
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn sqrt2() {
104        let r = brent_method(|x| x * x - 2.0, 0.0, 2.0, 1e-14).unwrap();
105        assert!((r - 2f64.sqrt()).abs() < 1e-12);
106    }
107
108    #[test]
109    fn steep_function() {
110        let r = brent_method(|x| (x - 1.0).powi(3) * 1e3, 0.0, 3.0, 1e-12).unwrap();
111        assert!((r - 1.0).abs() < 1e-3);
112    }
113
114    #[test]
115    fn rejects_same_sign() {
116        assert!(brent_method(|x| x * x + 1.0, -1.0, 1.0, 1e-9).is_err());
117    }
118}