quantlib_rs 0.1.0

A ground-up, idiomatic Rust quantitative finance library inspired by QuantLib.
Documentation
//! 1D Root-finding algorithms (Bisection and safeguarded Newton-Raphson).

use thiserror::Error;

/// Error type for root-finding solvers.
#[derive(Debug, Clone, PartialEq, Error)]
pub enum SolverError {
    /// Bracketing condition failed: f(min) and f(max) have the same sign.
    #[error("Roots are not bracketed: f({min})={f_min}, f({max})={f_max}")]
    NotBracketed {
        /// Lower bound
        min: f64,
        /// Upper bound
        max: f64,
        /// Function value at lower bound
        f_min: f64,
        /// Function value at upper bound
        f_max: f64,
    },
    /// Maximum iteration limit exceeded without reaching tolerance.
    #[error("Maximum iterations ({0}) exceeded")]
    MaxIterationsExceeded(usize),
    /// Derivative is zero or too close to zero during Newton-Raphson step.
    #[error("Derivative became zero during iteration at x={0}")]
    ZeroDerivative(f64),
}

/// 1D Bisection root finder.
///
/// Guaranteed to converge if root is bracketed ($f(\text{min}) \cdot f(\text{max}) \le 0$).
///
/// # Examples
/// ```
/// use quantlib_rs::math::solvers::Bisection;
///
/// // Find root of x^2 - 4 = 0 in [0, 5]
/// let root = Bisection::solve(|x| x * x - 4.0, 0.0, 5.0, 1e-10, 100).unwrap();
/// assert!((root - 2.0).abs() < 1e-9);
/// ```
pub struct Bisection;

impl Bisection {
    /// Solve for $x$ such that $f(x) = 0$ within $[min, max]$.
    pub fn solve<F: Fn(f64) -> f64>(
        f: F,
        mut min: f64,
        mut max: f64,
        tolerance: f64,
        max_iter: usize,
    ) -> Result<f64, SolverError> {
        let mut f_min = f(min);
        let f_max = f(max);

        if f_min.abs() <= tolerance {
            return Ok(min);
        }
        if f_max.abs() <= tolerance {
            return Ok(max);
        }

        if f_min * f_max > 0.0 {
            return Err(SolverError::NotBracketed {
                min,
                max,
                f_min,
                f_max,
            });
        }

        for iter in 0..max_iter {
            let mid = 0.5 * (min + max);
            let f_mid = f(mid);

            if f_mid.abs() <= tolerance || (max - min) <= tolerance {
                return Ok(mid);
            }

            if f_min * f_mid <= 0.0 {
                max = mid;
            } else {
                min = mid;
                f_min = f_mid;
            }

            if iter == max_iter - 1 {
                return Err(SolverError::MaxIterationsExceeded(max_iter));
            }
        }

        Err(SolverError::MaxIterationsExceeded(max_iter))
    }
}

/// Safeguarded Newton-Raphson root finder.
///
/// Combines the quadratic convergence of Newton-Raphson with interval bracketing.
/// If a Newton step would leave the bracket $[min, max]$ or fail to decrease the step
/// sufficiently, a bisection step is taken instead, preventing divergence.
///
/// # Examples
/// ```
/// use quantlib_rs::math::solvers::NewtonRaphson;
///
/// // Find root of x^3 - x - 2 = 0 (root approx 1.5213797)
/// let f = |x: f64| x.powi(3) - x - 2.0;
/// let df = |x: f64| 3.0 * x.powi(2) - 1.0;
///
/// let root = NewtonRaphson::solve(f, df, 1.0, 2.0, 1.5, 1e-10, 50).unwrap();
/// assert!((f(root)).abs() < 1e-9);
/// ```
pub struct NewtonRaphson;

impl NewtonRaphson {
    /// Solve $f(x) = 0$ using bracketed Newton-Raphson within $[min, max]$ starting from `guess`.
    pub fn solve<F, DF>(
        f: F,
        df: DF,
        mut min: f64,
        mut max: f64,
        guess: f64,
        tolerance: f64,
        max_iter: usize,
    ) -> Result<f64, SolverError>
    where
        F: Fn(f64) -> f64,
        DF: Fn(f64) -> f64,
    {
        let mut f_min = f(min);
        let f_max = f(max);

        if f_min.abs() <= tolerance {
            return Ok(min);
        }
        if f_max.abs() <= tolerance {
            return Ok(max);
        }

        if f_min * f_max > 0.0 {
            return Err(SolverError::NotBracketed {
                min,
                max,
                f_min,
                f_max,
            });
        }

        let mut x = guess.clamp(min, max);
        let mut dx_old = (max - min).abs();
        let mut dx = dx_old;

        for _ in 0..max_iter {
            let fx = f(x);
            let dfx = df(x);

            if fx.abs() <= tolerance {
                return Ok(x);
            }

            // Check whether Newton step is inside bracket and reducing step fast enough
            let step_out_of_bounds = ((x - min) * dfx - fx) * ((x - max) * dfx - fx) > 0.0;
            let step_not_converging = (2.0 * fx).abs() > (dx_old * dfx).abs();

            if step_out_of_bounds || step_not_converging || dfx.abs() < 1e-15 {
                // Fall back to bisection step
                dx_old = dx;
                dx = 0.5 * (max - min);
                x = min + dx;
            } else {
                // Take Newton step
                dx_old = dx;
                dx = fx / dfx;
                x -= dx;
            }

            if dx.abs() <= tolerance {
                return Ok(x);
            }

            let fx_new = f(x);
            if fx_new * f_min < 0.0 {
                max = x;
            } else {
                min = x;
                f_min = fx_new;
            }
        }

        Err(SolverError::MaxIterationsExceeded(max_iter))
    }
}