Skip to main content

lib_jsl_root_finding/
bracketing.rs

1//! Root bracketing.
2//!
3//! See the book entry [Bracketing methods](https://jwkunz.github.io/lib_jsl/book/root_finding/bracketing.html).
4
5use lib_jsl_core::ErrorsJSL;
6use crate::same_sign;
7
8/// Searches outward from the interval `[a, b]` for a sign change of `f`.
9///
10/// The interval is expanded geometrically (by a factor of 1.6 per step, on the side with the
11/// smaller `|f|`) for up to 50 iterations. Returns `(lo, hi)` with `f(lo) * f(hi) <= 0`.
12pub fn bracket_root<F>(f: F, a: f64, b: f64) -> Result<(f64, f64), ErrorsJSL>
13where
14    F: Fn(f64) -> f64,
15{
16    const FACTOR: f64 = 1.6;
17    const MAX_ITER: usize = 50;
18    if a == b || !a.is_finite() || !b.is_finite() {
19        return Err(ErrorsJSL::InvalidInputRange("bracket_root requires two distinct finite points"));
20    }
21    let (mut a, mut b) = if a < b { (a, b) } else { (b, a) };
22    let (mut fa, mut fb) = (f(a), f(b));
23    for _ in 0..MAX_ITER {
24        if !same_sign(fa, fb) {
25            return Ok((a, b));
26        }
27        if fa.abs() < fb.abs() {
28            a += FACTOR * (a - b);
29            fa = f(a);
30        } else {
31            b += FACTOR * (b - a);
32            fb = f(b);
33        }
34    }
35    Err(ErrorsJSL::RuntimeError("bracket_root failed to find a sign change"))
36}
37
38/// Divides `[a, b]` into `n` subintervals and returns every one containing a sign change (or a
39/// zero at an end, so a root exactly on a grid point is reported by both neighbouring intervals).
40/// Pairs of roots closer together than the spacing can cancel and go unnoticed.
41pub fn bracket_roots_scan<F>(f: F, a: f64, b: f64, n: usize) -> Vec<(f64, f64)>
42where
43    F: Fn(f64) -> f64,
44{
45    let mut out = Vec::new();
46    if n == 0 {
47        return out;
48    }
49    let dx = (b - a) / n as f64;
50    let mut x0 = a;
51    let mut f0 = f(x0);
52    for i in 1..=n {
53        let x1 = if i == n { b } else { a + dx * i as f64 };
54        let f1 = f(x1);
55        if !same_sign(f0, f1) {
56            out.push((x0, x1));
57        }
58        x0 = x1;
59        f0 = f1;
60    }
61    out
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn expands_to_bracket() {
70        let (lo, hi) = bracket_root(|x| x - 10.0, 0.0, 1.0).unwrap();
71        assert!((lo - 10.0) * (hi - 10.0) <= 0.0);
72    }
73
74    #[test]
75    fn fails_without_root() {
76        assert!(bracket_root(|x| x * x + 1.0, -1.0, 1.0).is_err());
77    }
78
79    #[test]
80    fn scan_finds_all() {
81        let r = bracket_roots_scan(|x: f64| x.sin(), 1.0, 10.0, 90);
82        assert_eq!(r.len(), 3); // pi, 2pi, 3pi
83    }
84}