Skip to main content

lib_jsl_root_finding/
false_position_method.rs

1//! False position method (Illinois variant).
2//!
3//! See the book entry [Bracketing methods](https://jwkunz.github.io/lib_jsl/book/root_finding/bracketing.html#false-position-and-the-illinois-modification).
4
5use lib_jsl_core::ErrorsJSL;
6use crate::same_sign;
7
8/// Finds a root of `f` in `[a, b]` by false position, using the Illinois modification to
9/// avoid stagnation of one endpoint. Requires a sign change over the interval.
10///
11/// Stops when the bracket is narrower than `tol` or `f` is exactly zero at the estimate; errors
12/// after 500 iterations.
13pub fn false_position<F>(f: F, a: f64, b: f64, tol: f64) -> Result<f64, ErrorsJSL>
14where
15    F: Fn(f64) -> f64,
16{
17    let (mut a, mut b) = (a, b);
18    let (mut fa, mut fb) = (f(a), f(b));
19    if fa == 0.0 {
20        return Ok(a);
21    }
22    if fb == 0.0 {
23        return Ok(b);
24    }
25    if !(fa < 0.0 && fb > 0.0 || fa > 0.0 && fb < 0.0) {
26        return Err(ErrorsJSL::InvalidInputRange("false_position: f(a) and f(b) must have opposite signs"));
27    }
28    let mut side = 0i8;
29    for _ in 0..500 {
30        let c = (a * fb - b * fa) / (fb - fa);
31        let fc = f(c);
32        if fc == 0.0 || (b - a).abs() < tol {
33            return Ok(c);
34        }
35        if same_sign(fc, fb) {
36            b = c;
37            fb = fc;
38            if side == -1 {
39                fa *= 0.5;
40            }
41            side = -1;
42        } else {
43            a = c;
44            fa = fc;
45            if side == 1 {
46                fb *= 0.5;
47            }
48            side = 1;
49        }
50        if (b - a).abs() < tol {
51            return Ok(c);
52        }
53    }
54    Err(ErrorsJSL::RuntimeError("false_position: failed to converge"))
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn cubic() {
63        let r = false_position(|x| x * x * x - x - 2.0, 1.0, 2.0, 1e-12).unwrap();
64        assert!((r * r * r - r - 2.0).abs() < 1e-9);
65    }
66
67    #[test]
68    fn rejects_same_sign() {
69        assert!(false_position(|x| x * x + 1.0, -1.0, 1.0, 1e-9).is_err());
70    }
71}