Skip to main content

lib_jsl_root_finding/
newton_raphson.rs

1//! Newton-Raphson 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).
4
5use lib_jsl_core::ErrorsJSL;
6/// Finds a root of `f` using Newton-Raphson iteration with derivative `df`, starting at `x0`.
7///
8/// Stops when a step `|f(x)/f'(x)|` is below `tol` (returning the updated iterate) or `f(x)` is
9/// exactly zero. Errors on a zero or non-finite derivative, divergence, or 100 iterations without
10/// convergence. Converges quadratically near a simple root, linearly near a repeated one.
11pub fn newton_raphson<F, D>(f: F, df: D, x0: f64, tol: f64) -> Result<f64, ErrorsJSL>
12where
13    F: Fn(f64) -> f64,
14    D: Fn(f64) -> f64,
15{
16    let mut x = x0;
17    // ANCHOR: newton
18    for _ in 0..100 {
19        let fx = f(x);
20        if fx == 0.0 {
21            return Ok(x);
22        }
23        let d = df(x);
24        if d == 0.0 || !d.is_finite() {
25            return Err(ErrorsJSL::RuntimeError("newton_raphson: derivative is zero or non-finite"));
26        }
27        let step = fx / d;
28        x -= step;
29        if !x.is_finite() {
30            return Err(ErrorsJSL::RuntimeError("newton_raphson: iterate diverged"));
31        }
32        if step.abs() < tol {
33            return Ok(x);
34        }
35    }
36    // ANCHOR_END: newton
37    Err(ErrorsJSL::RuntimeError("newton_raphson: failed to converge"))
38}
39
40#[cfg(test)]
41mod tests {
42    use super::*;
43
44    #[test]
45    fn sqrt2() {
46        let r = newton_raphson(|x| x * x - 2.0, |x| 2.0 * x, 1.0, 1e-14).unwrap();
47        assert!((r - 2f64.sqrt()).abs() < 1e-13);
48    }
49
50    #[test]
51    fn zero_derivative_errors() {
52        assert!(newton_raphson(|x| x * x + 1.0, |x| 2.0 * x, 0.0, 1e-9).is_err());
53    }
54}