use crate::error::{BarracudaError, Result};
pub fn bisect<F>(f: F, mut a: f64, mut b: f64, tol: f64, max_iter: usize) -> Result<f64>
where
F: Fn(f64) -> f64,
{
let mut fa = f(a);
let mut fb = f(b);
if fa * fb > 0.0 {
return Err(BarracudaError::InvalidInput {
message: format!(
"f(a) and f(b) must have opposite signs: f({a}) = {fa}, f({b}) = {fb}"
),
});
}
for iter in 0..max_iter {
let c = f64::midpoint(a, b);
let fc = f(c);
if (b - a).abs() < tol || fc.abs() < tol {
return Ok(c);
}
if fa * fc < 0.0 {
b = c;
fb = fc;
} else {
a = c;
fa = fc;
}
let _ = fb;
if iter == max_iter - 1 {
return Err(BarracudaError::ExecutionError {
message: format!(
"Bisection failed to converge in {max_iter} iterations, interval [{a}, {b}]"
),
});
}
}
Ok(f64::midpoint(a, b))
}
#[cfg(test)]
mod tests {
use super::*;
use std::f64::consts::PI;
#[test]
fn test_bisect_sqrt2() {
let f = |x: f64| x.mul_add(x, -2.0);
let root = bisect(f, 0.0, 2.0, 1e-10, 100).unwrap();
assert!((root - 2.0_f64.sqrt()).abs() < 1e-10);
}
#[test]
fn test_bisect_cubic() {
let f = |x: f64| x.powi(3) - x - 2.0;
let root = bisect(f, 1.0, 2.0, 1e-10, 100).unwrap();
assert!(f(root).abs() < 1e-9);
}
#[test]
fn test_bisect_sin() {
let f = |x: f64| x.sin();
let root = bisect(f, 3.0, 4.0, 1e-10, 100).unwrap();
assert!((root - PI).abs() < 1e-10);
}
#[test]
fn test_bisect_exp() {
let f = |x: f64| x.exp() - 2.0;
let root = bisect(f, 0.0, 1.0, 1e-10, 100).unwrap();
assert!((root - 2.0_f64.ln()).abs() < 1e-10);
}
#[test]
fn test_bisect_same_sign_error() {
let f = |x: f64| x - 1.0;
let result = bisect(f, 0.0, 0.5, 1e-10, 100);
assert!(result.is_err());
}
#[test]
fn test_bisect_max_iter_exceeded() {
let f = |x: f64| x.mul_add(x, -2.0);
let result = bisect(f, 0.0, 2.0, 1e-15, 5); assert!(result.is_err());
}
#[test]
fn test_bisect_exact_root() {
let f = |x: f64| x - 1.0;
let root = bisect(f, 0.0, 2.0, 1e-10, 100).unwrap();
assert!((root - 1.0).abs() < 1e-10);
}
}