Skip to main content

lib_jsl_root_finding/
mod.rs

1//! Root finding algorithms.
2//!
3//! See the book chapter [Root finding](https://jwkunz.github.io/lib_jsl/book/root_finding/index.html).
4
5pub mod bracketing;
6pub mod bisection;
7pub mod secant_method;
8pub mod false_position_method;
9pub mod ridders_method;
10pub mod van_wijngaarden_dekker_brent;
11pub mod newton_raphson;
12pub mod polynomial_roots;
13pub mod nonlinear_systems;
14pub mod newton_krylov;
15pub mod halley;
16pub mod fixed_point;
17pub mod minpack;
18
19/// `x * y > 0` without the product, which underflows to zero (or overflows) for extreme values.
20pub(crate) fn same_sign(x: f64, y: f64) -> bool {
21    (x > 0.0 && y > 0.0) || (x < 0.0 && y < 0.0)
22}
23
24pub use bracketing::{bracket_root, bracket_roots_scan};
25pub use bisection::bisection;
26pub use secant_method::secant_method;
27pub use false_position_method::false_position;
28pub use ridders_method::ridders_method;
29pub use van_wijngaarden_dekker_brent::brent_method;
30pub use newton_raphson::newton_raphson;
31pub use polynomial_roots::{polynomial_roots, polynomial_roots_complex};
32pub use nonlinear_systems::{SystemOptions, SystemRootResult, broyden_system, newton_system};
33pub use halley::halley;
34pub use fixed_point::{FixedPointMethod, fixed_point};
35pub use minpack::{JacobianFn, LmOptions, LmResult, leastsq, root_lm};
36pub use newton_krylov::{InnerSolver, NewtonKrylovOptions, NewtonKrylovResult, newton_krylov};
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn bracketing_methods_survive_tiny_and_huge_function_values() {
44        // The products f(a)·f(m) once underflowed to zero here, so bisection always kept the
45        // left half and converged to the right end of the bracket.
46        for scale in [1e-200, 1.0, 1e200] {
47            let f = |x: f64| scale * (x - 1.0 / 3.0);
48            for (name, r) in [
49                ("bisection", bisection(f, 0.0, 1.0, 1e-13)),
50                ("brent", brent_method(f, 0.0, 1.0, 1e-13)),
51                ("false position", false_position(f, 0.0, 1.0, 1e-13)),
52                ("ridders", ridders_method(f, 0.0, 1.0, 1e-13)),
53            ] {
54                let r = r.unwrap();
55                assert!((r - 1.0 / 3.0).abs() < 1e-12, "{name} at scale {scale:e}: {r}");
56            }
57            let (lo, hi) = bracket_root(f, 2.0, 3.0).unwrap();
58            assert!(lo <= 1.0 / 3.0 && 1.0 / 3.0 <= hi, "{scale:e}: {lo} {hi}");
59            assert_eq!(bracket_roots_scan(f, 0.0, 1.0, 10).len(), 1);
60        }
61        assert!(bisection(|_| f64::NAN, 0.0, 1.0, 1e-9).is_err());
62    }
63}