Skip to main content

moru_quant/math/
normal.rs

1//! Standard normal distribution: density, cumulative distribution function
2//! and its inverse.
3//!
4//! The CDF is W. J. Cody's `ANORM` (ACM TOMS Algorithm 715, 1993), built on
5//! W. J. Cody, "Rational Chebyshev approximations for the error function",
6//! Math. Comp. 23 (1969) 631–637. The inverse CDF is M. J. Wichura,
7//! "Algorithm AS 241: The percentage points of the normal distribution",
8//! Applied Statistics 37 (1988) 477–484 (`PPND16`). Coefficients are
9//! transcribed digit for digit from those sources.
10//!
11//! Accuracy is checked against 25-digit reference values in
12//! `tests/vectors/normal_*.txt` with a relative tolerance of `1e-14`.
13
14use crate::error::Error;
15
16/// `1 / sqrt(2π)`, as given in `ANORM` (`SQRPI`).
17#[allow(
18    clippy::excessive_precision,
19    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
20)]
21const FRAC_1_SQRT_2PI: f64 = 3.9894228040143267794e-1;
22
23/// `|x|` up to which `ANORM` uses its central approximation (`THRSH`):
24/// `0.46875·√2`, Cody's erf / erfc split point in the normal scale. (The
25/// source comment calls it the argument where the CDF is 0.75; that is
26/// `0.6745`.)
27const CDF_CENTRAL_LIMIT: f64 = 0.66291;
28
29/// `|x|` up to which `ANORM` uses its intermediate approximation
30/// (`ROOT32`: the source's `5.656854248` for `sqrt(32) = 5.6568542495…`).
31const CDF_INTERMEDIATE_LIMIT: f64 = 5.656854248;
32
33/// `|x|` beyond which the density and the lower tail are below the
34/// smallest subnormal `f64` (the density vanishes near `|x| = 38.6`, the
35/// lower tail near `38.5`).
36const UNDERFLOW_LIMIT: f64 = 40.0;
37
38/// Scale of the split `x = hi + lo` with `hi` a multiple of `1/16`
39/// (`ANORM`, `SIXTEN`).
40const SQUARE_SPLIT_SCALE: f64 = 16.0;
41
42// Rational approximations of `ANORM`, rearranged for Horner evaluation
43// (highest degree first). The source evaluates the same polynomials in the
44// same operation order: numerator `A(5), A(1), A(2), A(3), A(4)` over the
45// monic denominator `1, B(1), …, B(4)`, and likewise for `C`/`D` and `P`/`Q`.
46
47#[allow(
48    clippy::excessive_precision,
49    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
50)]
51const CDF_CENTRAL_NUM: [f64; 5] = [
52    6.5682337918207449113e-2,
53    2.2352520354606839287e00,
54    1.6102823106855587881e02,
55    1.0676894854603709582e03,
56    1.8154981253343561249e04,
57];
58
59#[allow(
60    clippy::excessive_precision,
61    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
62)]
63const CDF_CENTRAL_DEN: [f64; 5] = [
64    1.0,
65    4.7202581904688241870e01,
66    9.7609855173777669322e02,
67    1.0260932208618978205e04,
68    4.5507789335026729956e04,
69];
70
71#[allow(
72    clippy::excessive_precision,
73    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
74)]
75const CDF_INTERMEDIATE_NUM: [f64; 9] = [
76    1.0765576773720192317e-8,
77    3.9894151208813466764e-1,
78    8.8831497943883759412e00,
79    9.3506656132177855979e01,
80    5.9727027639480026226e02,
81    2.4945375852903726711e03,
82    6.8481904505362823326e03,
83    1.1602651437647350124e04,
84    9.8427148383839780218e03,
85];
86
87#[allow(
88    clippy::excessive_precision,
89    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
90)]
91const CDF_INTERMEDIATE_DEN: [f64; 9] = [
92    1.0,
93    2.2266688044328115691e01,
94    2.3538790178262499861e02,
95    1.5193775994075548050e03,
96    6.4855582982667607550e03,
97    1.8615571640885098091e04,
98    3.4900952721145977266e04,
99    3.8912003286093271411e04,
100    1.9685429676859990727e04,
101];
102
103#[allow(
104    clippy::excessive_precision,
105    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
106)]
107const CDF_TAIL_NUM: [f64; 6] = [
108    2.307344176494017303e-2,
109    2.1589853405795699e-1,
110    1.274011611602473639e-1,
111    2.2235277870649807e-2,
112    1.421619193227893466e-3,
113    2.9112874951168792e-5,
114];
115
116#[allow(
117    clippy::excessive_precision,
118    reason = "transcribed digit for digit from ANORM so it can be checked against the source"
119)]
120const CDF_TAIL_DEN: [f64; 6] = [
121    1.0,
122    1.28426009614491121e00,
123    4.68238212480865118e-1,
124    6.59881378689285515e-2,
125    3.78239633202758244e-3,
126    7.29751555083966205e-5,
127];
128
129/// `|p − 1/2|` up to which `PPND16` uses its central approximation
130/// (`SPLIT1`).
131const INVERSE_CENTRAL_LIMIT: f64 = 0.425;
132
133/// `SPLIT1²` (`CONST1`), the origin of the central variable.
134const INVERSE_CENTRAL_ORIGIN: f64 = 0.180625;
135
136/// `sqrt(−ln(tail))` up to which `PPND16` uses its intermediate
137/// approximation (`SPLIT2`); also the origin of the far-tail variable.
138const INVERSE_INTERMEDIATE_LIMIT: f64 = 5.0;
139
140/// Origin of the intermediate variable (`CONST2`).
141const INVERSE_INTERMEDIATE_ORIGIN: f64 = 1.6;
142
143// `PPND16` coefficients, highest degree first: `A7 … A0` over `B7 … B1, 1`,
144// and likewise for `C`/`D` and `E`/`F`.
145
146#[allow(
147    clippy::excessive_precision,
148    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
149)]
150const INVERSE_CENTRAL_NUM: [f64; 8] = [
151    2.5090809287301226727e+3,
152    3.3430575583588128105e+4,
153    6.7265770927008700853e+4,
154    4.5921953931549871457e+4,
155    1.3731693765509461125e+4,
156    1.9715909503065514427e+3,
157    1.3314166789178437745e+2,
158    3.3871328727963666080e0,
159];
160
161#[allow(
162    clippy::excessive_precision,
163    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
164)]
165const INVERSE_CENTRAL_DEN: [f64; 8] = [
166    5.2264952788528545610e+3,
167    2.8729085735721942674e+4,
168    3.9307895800092710610e+4,
169    2.1213794301586595867e+4,
170    5.3941960214247511077e+3,
171    6.8718700749205790830e+2,
172    4.2313330701600911252e+1,
173    1.0,
174];
175
176#[allow(
177    clippy::excessive_precision,
178    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
179)]
180const INVERSE_INTERMEDIATE_NUM: [f64; 8] = [
181    7.74545014278341407640e-4,
182    2.27238449892691845833e-2,
183    2.41780725177450611770e-1,
184    1.27045825245236838258e0,
185    3.64784832476320460504e0,
186    5.76949722146069140550e0,
187    4.63033784615654529590e0,
188    1.42343711074968357734e0,
189];
190
191#[allow(
192    clippy::excessive_precision,
193    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
194)]
195const INVERSE_INTERMEDIATE_DEN: [f64; 8] = [
196    1.05075007164441684324e-9,
197    5.47593808499534494600e-4,
198    1.51986665636164571966e-2,
199    1.48103976427480074590e-1,
200    6.89767334985100004550e-1,
201    1.67638483018380384940e0,
202    2.05319162663775882187e0,
203    1.0,
204];
205
206#[allow(
207    clippy::excessive_precision,
208    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
209)]
210const INVERSE_TAIL_NUM: [f64; 8] = [
211    2.01033439929228813265e-7,
212    2.71155556874348757815e-5,
213    1.24266094738807843860e-3,
214    2.65321895265761230930e-2,
215    2.96560571828504891230e-1,
216    1.78482653991729133580e0,
217    5.46378491116411436990e0,
218    6.65790464350110377720e0,
219];
220
221#[allow(
222    clippy::excessive_precision,
223    reason = "transcribed digit for digit from AS 241 so it can be checked against the source"
224)]
225const INVERSE_TAIL_DEN: [f64; 8] = [
226    2.04426310338993978564e-15,
227    1.42151175831644588870e-7,
228    1.84631831751005468180e-5,
229    7.86869131145613259100e-4,
230    1.48753612908506148525e-2,
231    1.36929880922735805310e-1,
232    5.99832206555887937690e-1,
233    1.0,
234];
235
236/// Standard normal probability density `φ(x) = exp(−x²/2) / sqrt(2π)`.
237///
238/// Defined for every `f64`: `NaN` gives `NaN`, `±∞` gives `0`. The relative
239/// error is below `1e-14` wherever the result is a normal `f64`
240/// (`|x| ≲ 37.5`); beyond that the result underflows gradually to `0`.
241///
242/// # Examples
243///
244/// ```
245/// use moru_quant::math::normal;
246///
247/// assert!((normal::pdf(0.0) - 0.398_942_280_401_432_7).abs() < 1e-16);
248/// ```
249pub fn pdf(x: f64) -> f64 {
250    let y = x.abs();
251    if y >= UNDERFLOW_LIMIT {
252        return 0.0;
253    }
254    FRAC_1_SQRT_2PI * exp_minus_half_square(y)
255}
256
257/// Standard normal cumulative distribution function
258/// `Φ(x) = P(Z ≤ x)` for `Z ~ N(0, 1)`.
259///
260/// Defined for every `f64`: `NaN` gives `NaN`, `−∞` gives `0`, `+∞` gives
261/// `1`. The relative error is below `1e-14` wherever the result is a normal
262/// `f64` (`x ≳ −37.5`); beyond that the result underflows gradually to `0`.
263/// The upper tail `Q(x) = 1 − Φ(x)` is computed accurately as `cdf(−x)`;
264/// `1.0 − cdf(x)` loses all precision once `Φ(x)` is close to `1`.
265///
266/// # Examples
267///
268/// ```
269/// use moru_quant::math::normal;
270///
271/// // Upper tail at 10 standard deviations, through the symmetry Q(x) = Φ(−x).
272/// let q = normal::cdf(-10.0);
273/// assert!((q / 7.619_853_024_160_527e-24 - 1.0).abs() < 1e-14);
274/// ```
275pub fn cdf(x: f64) -> f64 {
276    if x.is_nan() {
277        return x;
278    }
279    let y = x.abs();
280    if y <= CDF_CENTRAL_LIMIT {
281        let t = x * x;
282        return 0.5 + x * horner(t, &CDF_CENTRAL_NUM) / horner(t, &CDF_CENTRAL_DEN);
283    }
284    let lower_tail = if y <= CDF_INTERMEDIATE_LIMIT {
285        horner(y, &CDF_INTERMEDIATE_NUM) / horner(y, &CDF_INTERMEDIATE_DEN)
286            * exp_minus_half_square(y)
287    } else if y < UNDERFLOW_LIMIT {
288        let t = 1.0 / (y * y);
289        let ratio = t * horner(t, &CDF_TAIL_NUM) / horner(t, &CDF_TAIL_DEN);
290        (FRAC_1_SQRT_2PI - ratio) / y * exp_minus_half_square(y)
291    } else {
292        0.0
293    };
294    if x > 0.0 {
295        1.0 - lower_tail
296    } else {
297        lower_tail
298    }
299}
300
301/// Inverse of the standard normal CDF: the `x` with `Φ(x) = p`.
302///
303/// The relative error is below `1e-14` for every `p` in `(0, 1)`, including
304/// subnormal `p`.
305///
306/// # Errors
307///
308/// [`Error::ProbabilityOutOfRange`] if `p` is not strictly between `0` and
309/// `1` (including `NaN`); the infinite quantiles at `0` and `1` are not
310/// returned as values.
311///
312/// # Examples
313///
314/// ```
315/// use moru_quant::math::normal;
316///
317/// let x = normal::inverse_cdf(0.975)?;
318/// assert!((x - 1.959_963_984_540_054).abs() < 1e-14);
319/// # Ok::<(), moru_quant::Error>(())
320/// ```
321pub fn inverse_cdf(p: f64) -> Result<f64, Error> {
322    if p.is_nan() || p <= 0.0 || p >= 1.0 {
323        return Err(Error::ProbabilityOutOfRange { value: p });
324    }
325    let q = p - 0.5;
326    if q.abs() <= INVERSE_CENTRAL_LIMIT {
327        let r = INVERSE_CENTRAL_ORIGIN - q * q;
328        return Ok(q * horner(r, &INVERSE_CENTRAL_NUM) / horner(r, &INVERSE_CENTRAL_DEN));
329    }
330    // Exact for p ≥ 1/2 (Sterbenz), so the upper tail keeps full precision.
331    let tail = if q < 0.0 { p } else { 1.0 - p };
332    let r = (-tail.ln()).sqrt();
333    let magnitude = if r <= INVERSE_INTERMEDIATE_LIMIT {
334        let s = r - INVERSE_INTERMEDIATE_ORIGIN;
335        horner(s, &INVERSE_INTERMEDIATE_NUM) / horner(s, &INVERSE_INTERMEDIATE_DEN)
336    } else {
337        let s = r - INVERSE_INTERMEDIATE_LIMIT;
338        horner(s, &INVERSE_TAIL_NUM) / horner(s, &INVERSE_TAIL_DEN)
339    };
340    Ok(if q < 0.0 { -magnitude } else { magnitude })
341}
342
343/// `exp(−y²/2)` for `0 ≤ y < UNDERFLOW_LIMIT`, without the rounding error of
344/// `y²`.
345fn exp_minus_half_square(y: f64) -> f64 {
346    // Rounding y² costs a relative error of up to y²·ε/4 in the result
347    // (≈ 7.6e-14 at y = 37). With y = hi + lo and hi a multiple of 1/16,
348    // hi² is exact and lo·(2·hi + lo) is small (Cody, ANORM).
349    let hi = (y * SQUARE_SPLIT_SCALE).trunc() / SQUARE_SPLIT_SCALE;
350    let rest = (y - hi) * (y + hi);
351    (-hi * hi * 0.5).exp() * (-rest * 0.5).exp()
352}
353
354/// Polynomial with `coefficients` from the highest degree down, at `t`.
355fn horner(t: f64, coefficients: &[f64]) -> f64 {
356    coefficients.iter().fold(0.0, |acc, &c| acc * t + c)
357}