moru-quant 0.1.0

Rust library for quantitative finance and derivatives valuation: option pricing, implied volatility, Greeks, yield curves, and finite-difference / Monte Carlo engines.
Documentation
//! Standard normal distribution: density, cumulative distribution function
//! and its inverse.
//!
//! The CDF is W. J. Cody's `ANORM` (ACM TOMS Algorithm 715, 1993), built on
//! W. J. Cody, "Rational Chebyshev approximations for the error function",
//! Math. Comp. 23 (1969) 631–637. The inverse CDF is M. J. Wichura,
//! "Algorithm AS 241: The percentage points of the normal distribution",
//! Applied Statistics 37 (1988) 477–484 (`PPND16`). Coefficients are
//! transcribed digit for digit from those sources.
//!
//! Accuracy is checked against 25-digit reference values in
//! `tests/vectors/normal_*.txt` with a relative tolerance of `1e-14`.

use crate::error::Error;

/// `1 / sqrt(2π)`, as given in `ANORM` (`SQRPI`).
#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const FRAC_1_SQRT_2PI: f64 = 3.9894228040143267794e-1;

/// `|x|` up to which `ANORM` uses its central approximation (`THRSH`):
/// `0.46875·√2`, Cody's erf / erfc split point in the normal scale. (The
/// source comment calls it the argument where the CDF is 0.75; that is
/// `0.6745`.)
const CDF_CENTRAL_LIMIT: f64 = 0.66291;

/// `|x|` up to which `ANORM` uses its intermediate approximation
/// (`ROOT32`: the source's `5.656854248` for `sqrt(32) = 5.6568542495…`).
const CDF_INTERMEDIATE_LIMIT: f64 = 5.656854248;

/// `|x|` beyond which the density and the lower tail are below the
/// smallest subnormal `f64` (the density vanishes near `|x| = 38.6`, the
/// lower tail near `38.5`).
const UNDERFLOW_LIMIT: f64 = 40.0;

/// Scale of the split `x = hi + lo` with `hi` a multiple of `1/16`
/// (`ANORM`, `SIXTEN`).
const SQUARE_SPLIT_SCALE: f64 = 16.0;

// Rational approximations of `ANORM`, rearranged for Horner evaluation
// (highest degree first). The source evaluates the same polynomials in the
// same operation order: numerator `A(5), A(1), A(2), A(3), A(4)` over the
// monic denominator `1, B(1), …, B(4)`, and likewise for `C`/`D` and `P`/`Q`.

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const CDF_CENTRAL_NUM: [f64; 5] = [
    6.5682337918207449113e-2,
    2.2352520354606839287e00,
    1.6102823106855587881e02,
    1.0676894854603709582e03,
    1.8154981253343561249e04,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const CDF_CENTRAL_DEN: [f64; 5] = [
    1.0,
    4.7202581904688241870e01,
    9.7609855173777669322e02,
    1.0260932208618978205e04,
    4.5507789335026729956e04,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const CDF_INTERMEDIATE_NUM: [f64; 9] = [
    1.0765576773720192317e-8,
    3.9894151208813466764e-1,
    8.8831497943883759412e00,
    9.3506656132177855979e01,
    5.9727027639480026226e02,
    2.4945375852903726711e03,
    6.8481904505362823326e03,
    1.1602651437647350124e04,
    9.8427148383839780218e03,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const CDF_INTERMEDIATE_DEN: [f64; 9] = [
    1.0,
    2.2266688044328115691e01,
    2.3538790178262499861e02,
    1.5193775994075548050e03,
    6.4855582982667607550e03,
    1.8615571640885098091e04,
    3.4900952721145977266e04,
    3.8912003286093271411e04,
    1.9685429676859990727e04,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const CDF_TAIL_NUM: [f64; 6] = [
    2.307344176494017303e-2,
    2.1589853405795699e-1,
    1.274011611602473639e-1,
    2.2235277870649807e-2,
    1.421619193227893466e-3,
    2.9112874951168792e-5,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
)]
const CDF_TAIL_DEN: [f64; 6] = [
    1.0,
    1.28426009614491121e00,
    4.68238212480865118e-1,
    6.59881378689285515e-2,
    3.78239633202758244e-3,
    7.29751555083966205e-5,
];

/// `|p − 1/2|` up to which `PPND16` uses its central approximation
/// (`SPLIT1`).
const INVERSE_CENTRAL_LIMIT: f64 = 0.425;

/// `SPLIT1²` (`CONST1`), the origin of the central variable.
const INVERSE_CENTRAL_ORIGIN: f64 = 0.180625;

/// `sqrt(−ln(tail))` up to which `PPND16` uses its intermediate
/// approximation (`SPLIT2`); also the origin of the far-tail variable.
const INVERSE_INTERMEDIATE_LIMIT: f64 = 5.0;

/// Origin of the intermediate variable (`CONST2`).
const INVERSE_INTERMEDIATE_ORIGIN: f64 = 1.6;

// `PPND16` coefficients, highest degree first: `A7 … A0` over `B7 … B1, 1`,
// and likewise for `C`/`D` and `E`/`F`.

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
)]
const INVERSE_CENTRAL_NUM: [f64; 8] = [
    2.5090809287301226727e+3,
    3.3430575583588128105e+4,
    6.7265770927008700853e+4,
    4.5921953931549871457e+4,
    1.3731693765509461125e+4,
    1.9715909503065514427e+3,
    1.3314166789178437745e+2,
    3.3871328727963666080e0,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
)]
const INVERSE_CENTRAL_DEN: [f64; 8] = [
    5.2264952788528545610e+3,
    2.8729085735721942674e+4,
    3.9307895800092710610e+4,
    2.1213794301586595867e+4,
    5.3941960214247511077e+3,
    6.8718700749205790830e+2,
    4.2313330701600911252e+1,
    1.0,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
)]
const INVERSE_INTERMEDIATE_NUM: [f64; 8] = [
    7.74545014278341407640e-4,
    2.27238449892691845833e-2,
    2.41780725177450611770e-1,
    1.27045825245236838258e0,
    3.64784832476320460504e0,
    5.76949722146069140550e0,
    4.63033784615654529590e0,
    1.42343711074968357734e0,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
)]
const INVERSE_INTERMEDIATE_DEN: [f64; 8] = [
    1.05075007164441684324e-9,
    5.47593808499534494600e-4,
    1.51986665636164571966e-2,
    1.48103976427480074590e-1,
    6.89767334985100004550e-1,
    1.67638483018380384940e0,
    2.05319162663775882187e0,
    1.0,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
)]
const INVERSE_TAIL_NUM: [f64; 8] = [
    2.01033439929228813265e-7,
    2.71155556874348757815e-5,
    1.24266094738807843860e-3,
    2.65321895265761230930e-2,
    2.96560571828504891230e-1,
    1.78482653991729133580e0,
    5.46378491116411436990e0,
    6.65790464350110377720e0,
];

#[allow(
    clippy::excessive_precision,
    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
)]
const INVERSE_TAIL_DEN: [f64; 8] = [
    2.04426310338993978564e-15,
    1.42151175831644588870e-7,
    1.84631831751005468180e-5,
    7.86869131145613259100e-4,
    1.48753612908506148525e-2,
    1.36929880922735805310e-1,
    5.99832206555887937690e-1,
    1.0,
];

/// Standard normal probability density `φ(x) = exp(−x²/2) / sqrt(2π)`.
///
/// Defined for every `f64`: `NaN` gives `NaN`, `±∞` gives `0`. The relative
/// error is below `1e-14` wherever the result is a normal `f64`
/// (`|x| ≲ 37.5`); beyond that the result underflows gradually to `0`.
///
/// # Examples
///
/// ```
/// use moru_quant::math::normal;
///
/// assert!((normal::pdf(0.0) - 0.398_942_280_401_432_7).abs() < 1e-16);
/// ```
pub fn pdf(x: f64) -> f64 {
    let y = x.abs();
    if y >= UNDERFLOW_LIMIT {
        return 0.0;
    }
    FRAC_1_SQRT_2PI * exp_minus_half_square(y)
}

/// Standard normal cumulative distribution function
/// `Φ(x) = P(Z ≤ x)` for `Z ~ N(0, 1)`.
///
/// Defined for every `f64`: `NaN` gives `NaN`, `−∞` gives `0`, `+∞` gives
/// `1`. The relative error is below `1e-14` wherever the result is a normal
/// `f64` (`x ≳ −37.5`); beyond that the result underflows gradually to `0`.
/// The upper tail `Q(x) = 1 − Φ(x)` is computed accurately as `cdf(−x)`;
/// `1.0 − cdf(x)` loses all precision once `Φ(x)` is close to `1`.
///
/// # Examples
///
/// ```
/// use moru_quant::math::normal;
///
/// // Upper tail at 10 standard deviations, through the symmetry Q(x) = Φ(−x).
/// let q = normal::cdf(-10.0);
/// assert!((q / 7.619_853_024_160_527e-24 - 1.0).abs() < 1e-14);
/// ```
pub fn cdf(x: f64) -> f64 {
    if x.is_nan() {
        return x;
    }
    let y = x.abs();
    if y <= CDF_CENTRAL_LIMIT {
        let t = x * x;
        return 0.5 + x * horner(t, &CDF_CENTRAL_NUM) / horner(t, &CDF_CENTRAL_DEN);
    }
    let lower_tail = if y <= CDF_INTERMEDIATE_LIMIT {
        horner(y, &CDF_INTERMEDIATE_NUM) / horner(y, &CDF_INTERMEDIATE_DEN)
            * exp_minus_half_square(y)
    } else if y < UNDERFLOW_LIMIT {
        let t = 1.0 / (y * y);
        let ratio = t * horner(t, &CDF_TAIL_NUM) / horner(t, &CDF_TAIL_DEN);
        (FRAC_1_SQRT_2PI - ratio) / y * exp_minus_half_square(y)
    } else {
        0.0
    };
    if x > 0.0 {
        1.0 - lower_tail
    } else {
        lower_tail
    }
}

/// Inverse of the standard normal CDF: the `x` with `Φ(x) = p`.
///
/// The relative error is below `1e-14` for every `p` in `(0, 1)`, including
/// subnormal `p`.
///
/// # Errors
///
/// [`Error::ProbabilityOutOfRange`] if `p` is not strictly between `0` and
/// `1` (including `NaN`); the infinite quantiles at `0` and `1` are not
/// returned as values.
///
/// # Examples
///
/// ```
/// use moru_quant::math::normal;
///
/// let x = normal::inverse_cdf(0.975)?;
/// assert!((x - 1.959_963_984_540_054).abs() < 1e-14);
/// # Ok::<(), moru_quant::Error>(())
/// ```
pub fn inverse_cdf(p: f64) -> Result<f64, Error> {
    if p.is_nan() || p <= 0.0 || p >= 1.0 {
        return Err(Error::ProbabilityOutOfRange { value: p });
    }
    let q = p - 0.5;
    if q.abs() <= INVERSE_CENTRAL_LIMIT {
        let r = INVERSE_CENTRAL_ORIGIN - q * q;
        return Ok(q * horner(r, &INVERSE_CENTRAL_NUM) / horner(r, &INVERSE_CENTRAL_DEN));
    }
    // Exact for p ≥ 1/2 (Sterbenz), so the upper tail keeps full precision.
    let tail = if q < 0.0 { p } else { 1.0 - p };
    let r = (-tail.ln()).sqrt();
    let magnitude = if r <= INVERSE_INTERMEDIATE_LIMIT {
        let s = r - INVERSE_INTERMEDIATE_ORIGIN;
        horner(s, &INVERSE_INTERMEDIATE_NUM) / horner(s, &INVERSE_INTERMEDIATE_DEN)
    } else {
        let s = r - INVERSE_INTERMEDIATE_LIMIT;
        horner(s, &INVERSE_TAIL_NUM) / horner(s, &INVERSE_TAIL_DEN)
    };
    Ok(if q < 0.0 { -magnitude } else { magnitude })
}

/// `exp(−y²/2)` for `0 ≤ y < UNDERFLOW_LIMIT`, without the rounding error of
/// `y²`.
fn exp_minus_half_square(y: f64) -> f64 {
    // Rounding y² costs a relative error of up to y²·ε/4 in the result
    // (≈ 7.6e-14 at y = 37). With y = hi + lo and hi a multiple of 1/16,
    // hi² is exact and lo·(2·hi + lo) is small (Cody, ANORM).
    let hi = (y * SQUARE_SPLIT_SCALE).trunc() / SQUARE_SPLIT_SCALE;
    let rest = (y - hi) * (y + hi);
    (-hi * hi * 0.5).exp() * (-rest * 0.5).exp()
}

/// Polynomial with `coefficients` from the highest degree down, at `t`.
fn horner(t: f64, coefficients: &[f64]) -> f64 {
    coefficients.iter().fold(0.0, |acc, &c| acc * t + c)
}