Skip to main content

lib_jsl_root_finding/
halley.rs

1//! Halley's method (SciPy's `newton` given `fprime2`), cubically convergent with the second
2//! derivative.
3//!
4//! See the book entry [Halley's method and fixed points](https://jwkunz.github.io/lib_jsl/book/root_finding/halley-fixed-point.html).
5
6use lib_jsl_core::ErrorsJSL;
7
8// ANCHOR: halley
9/// Finds a root of `f` by Halley's method from `x0`, as SciPy's `newton` with `fprime2`: the
10/// Newton step `δ = f/f'` is divided by `1 − δ f''/(2f')` whenever that correction is below one
11/// in magnitude. Stops when successive iterates differ by at most `tol` (SciPy's default is
12/// 1.48·10⁻⁸) or `f(x)` is exactly zero; errors on a zero derivative or after 50 iterations.
13/// Converges cubically near a simple root.
14pub fn halley<F, D, D2>(f: F, df: D, d2f: D2, x0: f64, tol: f64) -> Result<f64, ErrorsJSL>
15where
16    F: Fn(f64) -> f64,
17    D: Fn(f64) -> f64,
18    D2: Fn(f64) -> f64,
19{
20    let mut x = x0;
21    for _ in 0..50 {
22        let fx = f(x);
23        if fx == 0.0 {
24            return Ok(x);
25        }
26        let d = df(x);
27        if d == 0.0 || !d.is_finite() {
28            return Err(ErrorsJSL::RuntimeError("halley: derivative is zero or non-finite"));
29        }
30        let mut step = fx / d;
31        let adj = step * d2f(x) / d / 2.0;
32        if adj.abs() < 1.0 {
33            step /= 1.0 - adj;
34        }
35        let next = x - step;
36        if !next.is_finite() {
37            return Err(ErrorsJSL::RuntimeError("halley: iterate diverged"));
38        }
39        if (next - x).abs() <= tol {
40            return Ok(next);
41        }
42        x = next;
43    }
44    Err(ErrorsJSL::RuntimeError("halley: failed to converge in 50 iterations"))
45}
46// ANCHOR_END: halley
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn cubic_convergence() {
54        // Count the iterations Halley needs for the cube root of 10, against Newton.
55        let calls = std::cell::Cell::new(0);
56        let f = |x: f64| {
57            calls.set(calls.get() + 1);
58            x * x * x - 10.0
59        };
60        let r = halley(f, |x| 3.0 * x * x, |x| 6.0 * x, 1.0, 1e-15).unwrap();
61        assert!((r - 10f64.cbrt()).abs() < 1e-15);
62        assert!(calls.get() <= 6, "{}", calls.get());
63        assert!(halley(|x| x * x + 1.0, |x| 2.0 * x, |_| 2.0, 0.0, 1e-9).is_err());
64    }
65}