Skip to main content

lib_jsl_root_finding/
secant_method.rs

1//! Secant method.
2//!
3//! See the book entry [Newton's method and the secant method](https://jwkunz.github.io/lib_jsl/book/root_finding/newton.html#the-secant-method).
4
5use lib_jsl_core::ErrorsJSL;
6/// Finds a root of `f` with the secant method starting from `x0` and `x1`.
7///
8/// Stops when `f` is exactly zero, or successive iterates differ by less than `tol` and either `f`
9/// changes sign between them or their own secant slope places the root within `tol`. Errors on a
10/// zero secant slope, divergence, or 100 iterations without convergence. The order of convergence
11/// near a simple root is the golden ratio, 1.618.
12pub fn secant_method<F>(f: F, x0: f64, x1: f64, tol: f64) -> Result<f64, ErrorsJSL>
13where
14    F: Fn(f64) -> f64,
15{
16    let (mut x0, mut x1) = (x0, x1);
17    let (mut f0, mut f1) = (f(x0), f(x1));
18    for _ in 0..100 {
19        if f1 == 0.0 {
20            return Ok(x1);
21        }
22        if f1 == f0 {
23            return Err(ErrorsJSL::RuntimeError("secant_method: zero slope between iterates"));
24        }
25        // ANCHOR: secant
26        let mut x2 = x1 - f1 * (x1 - x0) / (f1 - f0);
27        if !x2.is_finite() {
28            return Err(ErrorsJSL::RuntimeError("secant_method: iterate diverged"));
29        }
30        let small = (x2 - x1).abs() < tol;
31        if x2 == x1 {
32            // A zero step gives no local slope to check it with: probe a little way off.
33            let h = (0.5 * tol).max(4.0 * f64::EPSILON * x1.abs()).max(f64::MIN_POSITIVE);
34            x2 = if x0 > x1 { x1 + h } else { x1 - h };
35        }
36        let f2 = f(x2);
37        // A small step is convergence only if f changes sign across it, or the slope between these
38        // two nearby points (not the secant through a distant earlier point, which can make the
39        // step tiny anywhere) puts the root within `tol`.
40        if f2 == 0.0 || (small && (f2.signum() != f1.signum() || (f2 * (x2 - x1)).abs() <= (tol * (f2 - f1)).abs())) {
41            return Ok(x2);
42        }
43        // ANCHOR_END: secant
44        (x0, f0, x1, f1) = (x1, f1, x2, f2);
45    }
46    Err(ErrorsJSL::RuntimeError("secant_method: failed to converge"))
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn cos_root() {
55        let r = secant_method(|x| x.cos() - x, 0.0, 1.0, 1e-12).unwrap();
56        assert!((r - 0.7390851332151607).abs() < 1e-10);
57    }
58
59    #[test]
60    fn a_tiny_step_after_a_wild_one_is_not_convergence() {
61        // From 0 and 1.3, x¹⁰ − 1 throws an iterate to 2.2e6; the secant through it gives a step of
62        // 1e-10 at x = 0.18, which was once returned as a root.
63        let r = secant_method(|x| x.powi(10) - 1.0, 0.0, 1.3, 1e-13);
64        assert!(r.as_ref().map_or(true, |x| (x.abs() - 1.0).abs() < 1e-12), "{r:?}");
65    }
66
67    #[test]
68    fn flat_function_errors() {
69        assert!(secant_method(|_| 1.0, 0.0, 1.0, 1e-9).is_err());
70    }
71}