one-indexed-vec 0.2.0

A one-based (1-indexed) wrapper around Vec<T>: element at position N is accessed via vec[N].
Documentation
//! Root finding.

/// Bisection on `[a, b]`. Returns `None` if no sign change.
pub fn bisection<F>(f: F, mut a: f64, mut b: f64, tol: f64, max_iter: usize) -> Option<f64>
where
    F: Fn(f64) -> f64,
{
    let mut fa = f(a);
    let fb = f(b);
    if fa * fb > 0.0 {
        return None;
    }
    for _ in 0..max_iter {
        let m = 0.5 * (a + b);
        let fm = f(m);
        if fm.abs() < tol || (b - a) * 0.5 < tol {
            return Some(m);
        }
        if fa * fm < 0.0 {
            b = m;
        } else {
            a = m;
            fa = fm;
        }
    }
    Some(0.5 * (a + b))
}

/// Newton's method. `df` is the derivative of `f`.
pub fn newton<F, D>(f: F, df: D, mut x: f64, tol: f64, max_iter: usize) -> Option<f64>
where
    F: Fn(f64) -> f64,
    D: Fn(f64) -> f64,
{
    for _ in 0..max_iter {
        let fx = f(x);
        if fx.abs() < tol {
            return Some(x);
        }
        let dfx = df(x);
        if dfx.abs() < f64::EPSILON {
            return None;
        }
        x -= fx / dfx;
    }
    Some(x)
}

/// Secant method.
pub fn secant<F>(f: F, mut x0: f64, mut x1: f64, tol: f64, max_iter: usize) -> Option<f64>
where
    F: Fn(f64) -> f64,
{
    for _ in 0..max_iter {
        let f0 = f(x0);
        let f1 = f(x1);
        if f1.abs() < tol {
            return Some(x1);
        }
        let denom = f1 - f0;
        if denom.abs() < f64::EPSILON {
            return None;
        }
        let x2 = x1 - f1 * (x1 - x0) / denom;
        x0 = x1;
        x1 = x2;
    }
    Some(x1)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bisection_sqrt2() {
        let r = bisection(|x| x * x - 2.0, 0.0, 2.0, 1e-12, 100).unwrap();
        assert!((r - 2.0f64.sqrt()).abs() < 1e-10);
    }

    #[test]
    fn newton_sqrt2() {
        let r = newton(|x| x * x - 2.0, |x| 2.0 * x, 1.0, 1e-12, 100).unwrap();
        assert!((r - 2.0f64.sqrt()).abs() < 1e-10);
    }

    #[test]
    fn secant_sqrt2() {
        let r = secant(|x| x * x - 2.0, 0.0, 2.0, 1e-12, 100).unwrap();
        assert!((r - 2.0f64.sqrt()).abs() < 1e-8);
    }
}