Skip to main content

gamlss_special/
lib.rs

1#![forbid(unsafe_code)]
2//! Special functions and numerical helpers for GAMLSS crates.
3//!
4//! This crate intentionally exposes small scalar `f64` free functions. Keeping
5//! the API as free functions lets distribution crates call them without runtime
6//! dispatch while still sharing one implementation of gamma/beta, normal-tail
7//! and CDF inversion helpers.
8//!
9//! Invalid domains return `NaN` for helper-style APIs and non-finite likelihood
10//! scale values where that convention is already part of the surrounding
11//! distribution code.
12
13const LANCZOS_SHIFT: f64 = 6.5;
14const EULER_MASCHERONI: f64 = 0.577_215_664_901_532_9;
15const HALF_LOG_2_PI: f64 = 0.918_938_533_204_672_7;
16const INV_SQRT_2_PI: f64 = 0.398_942_280_401_432_7;
17
18const LANCZOS_COEFFICIENTS: [f64; 9] = [
19    0.999_999_999_999_809_9,
20    676.520_368_121_885_1,
21    -1_259.139_216_722_402_8,
22    771.323_428_777_653_1,
23    -176.615_029_162_140_6,
24    12.507_343_278_686_905,
25    -0.138_571_095_265_720_12,
26    9.984_369_578_019_572e-6,
27    1.505_632_735_149_311_6e-7,
28];
29
30#[inline]
31fn is_probability(value: f64) -> bool {
32    (0.0..=1.0).contains(&value) && value.is_finite()
33}
34
35#[inline]
36const fn clamp_probability(value: f64) -> f64 {
37    value.clamp(0.0, 1.0)
38}
39
40#[inline]
41fn polynomial_ascending(value: f64, coefficients: &[f64]) -> f64 {
42    // AS241 coefficients below are stored from constant term to highest degree.
43    coefficients
44        .iter()
45        .rev()
46        .fold(0.0, |accumulator, coefficient| {
47            accumulator * value + coefficient
48        })
49}
50
51#[inline]
52fn polynomial_ascending_with_constant_one(value: f64, coefficients: &[f64]) -> f64 {
53    value.mul_add(polynomial_ascending(value, coefficients), 1.0)
54}
55
56#[inline]
57fn polynomial_descending(value: f64, coefficients: &[f64]) -> f64 {
58    // Cody/Cephes coefficients below are stored from highest degree to constant term.
59    coefficients.iter().fold(0.0, |accumulator, coefficient| {
60        accumulator * value + coefficient
61    })
62}
63
64#[inline]
65fn polynomial_descending_with_implicit_leading_one(value: f64, coefficients: &[f64]) -> f64 {
66    let Some((&first, rest)) = coefficients.split_first() else {
67        return value;
68    };
69
70    rest.iter().fold(value + first, |accumulator, coefficient| {
71        accumulator * value + coefficient
72    })
73}
74
75#[inline]
76fn lanczos_sum(value: f64) -> f64 {
77    let shifted = value - 1.0;
78    let mut sum = LANCZOS_COEFFICIENTS[0];
79
80    #[allow(clippy::cast_precision_loss)]
81    for (index, coefficient) in LANCZOS_COEFFICIENTS.iter().copied().enumerate().skip(1) {
82        sum += coefficient / (shifted + index as f64);
83    }
84
85    sum
86}
87
88/// Natural logarithm of the absolute gamma function via the Lanczos approximation.
89///
90/// Returns `NaN` at poles and for non-finite negative inputs. For positive
91/// inputs this is the usual `ln(Gamma(x))`; for negative non-integers it is
92/// `ln(abs(Gamma(x)))`.
93#[must_use]
94#[inline]
95pub fn ln_gamma(value: f64) -> f64 {
96    if value == f64::INFINITY {
97        return f64::INFINITY;
98    }
99    if !value.is_finite() || (value <= 0.0 && value.fract() == 0.0) {
100        return f64::NAN;
101    }
102
103    if value < 0.5 {
104        let sin_pi = (std::f64::consts::PI * value).sin();
105        if sin_pi == 0.0 {
106            return f64::NAN;
107        }
108        return std::f64::consts::PI.ln() - sin_pi.abs().ln() - ln_gamma(1.0 - value);
109    }
110
111    let x = lanczos_sum(value);
112    let t = value + LANCZOS_SHIFT;
113
114    (value - 0.5).mul_add(t.ln(), HALF_LOG_2_PI) - t + x.ln()
115}
116
117/// Difference `ln(Gamma(base + increment)) - ln(Gamma(base))` for positive arguments.
118///
119/// This avoids cancellation when `base` is large and `increment` is small, which is common in beta normalizing constants and gamma-ratio terms.
120#[must_use]
121#[inline]
122pub fn ln_gamma_delta(base: f64, increment: f64) -> f64 {
123    if base <= 0.0 || increment < 0.0 || !base.is_finite() || !increment.is_finite() {
124        return f64::NAN;
125    }
126    if increment == 0.0 {
127        return 0.0;
128    }
129
130    let target = base + increment;
131    if !target.is_finite() {
132        return f64::INFINITY;
133    }
134    if base < 0.5 {
135        return ln_gamma(target) - ln_gamma(base);
136    }
137
138    let t = base + LANCZOS_SHIFT;
139    let log_power = increment.mul_add(t.ln(), (target - 0.5) * (increment / t).ln_1p());
140    log_power - increment + (lanczos_sum(target) / lanczos_sum(base)).ln()
141}
142
143/// Residual `ln(Gamma(x)) - x * ln(x) + x` for positive finite `x`.
144///
145/// The direct expression catastrophically cancels for large `x`; the
146/// Stirling series keeps the logarithmic remainder representable.
147#[must_use]
148#[inline]
149pub fn ln_gamma_stirling_residual(value: f64) -> f64 {
150    if value <= 0.0 || !value.is_finite() {
151        return f64::NAN;
152    }
153    if value < 8.0 {
154        return value.mul_add(1.0 - value.ln(), ln_gamma(value));
155    }
156
157    let inverse = 1.0 / value;
158    let inverse2 = inverse * inverse;
159    let inverse3 = inverse2 * inverse;
160    let inverse5 = inverse3 * inverse2;
161    let inverse7 = inverse5 * inverse2;
162    let inverse9 = inverse7 * inverse2;
163    let inverse11 = inverse9 * inverse2;
164    0.5f64.mul_add(-value.ln(), HALF_LOG_2_PI) + inverse / 12.0 - inverse3 / 360.0
165        + inverse5 / 1_260.0
166        - inverse7 / 1_680.0
167        + inverse9 / 1_188.0
168        - 691.0 * inverse11 / 360_360.0
169}
170
171/// Natural logarithm of the beta function for positive finite arguments.
172#[must_use]
173#[inline]
174pub fn ln_beta(a: f64, b: f64) -> f64 {
175    if a <= 0.0 || b <= 0.0 || !a.is_finite() || !b.is_finite() {
176        return f64::NAN;
177    }
178
179    let small = a.min(b);
180    let large = a.max(b);
181    ln_gamma(small) - ln_gamma_delta(large, small)
182}
183
184/// Logarithm of the multivariate beta function.
185///
186/// The sequential beta identity avoids subtracting one large `ln_gamma(sum)`
187/// from a separately accumulated sum of large gamma terms.
188#[must_use]
189pub fn ln_multivariate_beta(alpha: &[f64]) -> f64 {
190    if alpha.len() < 2
191        || alpha
192            .iter()
193            .any(|value| !value.is_finite() || *value <= 0.0)
194    {
195        return f64::NAN;
196    }
197
198    let mut prefix = alpha[0];
199    let mut value = 0.0;
200    for component in alpha.iter().copied().skip(1) {
201        value += ln_beta(prefix, component);
202        prefix += component;
203        if !prefix.is_finite() {
204            return f64::NAN;
205        }
206    }
207    value
208}
209
210/// Baseline softmax with a representable strictly-positive result.
211///
212/// The final logit is fixed to zero. Finite logit differences that would make
213/// `exp` underflow are saturated at the smallest normal exponent, preserving
214/// the interior-simplex invariant in `f64`.
215#[must_use]
216pub fn baseline_softmax<const D: usize>(mut logits: [f64; D]) -> [f64; D] {
217    if D == 0 || logits.iter().any(|value| !value.is_finite()) {
218        return [f64::NAN; D];
219    }
220    logits[D - 1] = 0.0;
221    let max = logits.iter().copied().fold(f64::NEG_INFINITY, f64::max);
222    let min_exponent = f64::MIN_POSITIVE.ln();
223    let mut weights = [0.0; D];
224    let mut sum = 0.0;
225    for (weight, logit) in weights.iter_mut().zip(logits) {
226        *weight = (logit - max).max(min_exponent).exp();
227        sum += *weight;
228    }
229    for weight in &mut weights {
230        *weight /= sum;
231    }
232    weights
233}
234
235/// Returns `true` for finite counts represented on the shared `f64` observation path.
236#[must_use]
237#[inline]
238pub fn is_nonnegative_integer(value: f64) -> bool {
239    value >= 0.0 && value.is_finite() && value.fract() == 0.0
240}
241
242/// Converts a finite CDF query point into the largest included count.
243///
244/// Returning `None` for non-finite or excessively large query points keeps
245/// discrete CDF implementations from doing unbounded work.
246#[must_use]
247#[inline]
248#[allow(
249    clippy::cast_precision_loss,
250    clippy::cast_possible_truncation,
251    clippy::cast_sign_loss
252)]
253pub fn included_count(value: f64, max_terms: u64) -> Option<u64> {
254    if !value.is_finite() {
255        return None;
256    }
257    if value < 0.0 {
258        return Some(0);
259    }
260
261    let count = value.floor();
262    if count > max_terms as f64 {
263        None
264    } else {
265        Some(count as u64)
266    }
267}
268
269/// Stable two-term log-space addition.
270#[must_use]
271#[inline]
272pub fn log_add_exp(log_left: f64, log_right: f64) -> f64 {
273    if log_left.is_nan() || log_right.is_nan() {
274        return f64::NAN;
275    }
276    if log_left == f64::NEG_INFINITY {
277        return log_right;
278    }
279    if log_right == f64::NEG_INFINITY {
280        return log_left;
281    }
282    if log_left == f64::INFINITY || log_right == f64::INFINITY {
283        return f64::INFINITY;
284    }
285
286    let max = log_left.max(log_right);
287    max + (-(log_left - log_right).abs()).exp().ln_1p()
288}
289
290/// Kullback-Leibler divergence between Bernoulli probabilities.
291///
292/// Both probabilities must lie strictly inside `(0, 1)`. A local series
293/// preserves the quadratic divergence when the probabilities are nearly
294/// equal and the two first-order log terms would otherwise cancel.
295#[must_use]
296pub fn bernoulli_kl(probability: f64, reference: f64) -> f64 {
297    if !(0.0..1.0).contains(&probability)
298        || !(0.0..1.0).contains(&reference)
299        || !probability.is_finite()
300        || !reference.is_finite()
301    {
302        return f64::NAN;
303    }
304
305    let complement = 1.0 - probability;
306    let difference = reference - probability;
307    let relative_probability = difference / probability;
308    let relative_complement = -difference / complement;
309    if relative_probability.abs().max(relative_complement.abs()) <= 0.25 {
310        let mut probability_power = relative_probability * relative_probability;
311        let mut complement_power = relative_complement * relative_complement;
312        let mut sum = 0.0;
313        for order in 2..=128 {
314            let order_f = f64::from(order);
315            let sign = if order % 2 == 0 { 1.0 } else { -1.0 };
316            let term = sign * probability.mul_add(probability_power, complement * complement_power)
317                / order_f;
318            let magnitude = probability
319                .mul_add(probability_power.abs(), complement * complement_power.abs())
320                / order_f;
321            sum += term;
322            if magnitude <= f64::EPSILON * sum.abs() {
323                break;
324            }
325            probability_power *= relative_probability;
326            complement_power *= relative_complement;
327        }
328        sum.max(0.0)
329    } else {
330        (-probability).mul_add(
331            relative_probability.ln_1p(),
332            -complement * relative_complement.ln_1p(),
333        )
334    }
335}
336
337/// Kullback-Leibler divergence between categorical probability vectors.
338///
339/// `probability` may lie on the simplex boundary, while every `reference` component must be strictly positive. The vectors are expected to have the same normalization; a local series preserves the divergence when their components are nearly equal and direct log-ratio terms would cancel.
340///
341/// Returns `NaN` for an empty vector, a negative or non-finite probability, a non-positive or non-finite reference component, a non-finite component sum, or an all-zero probability vector.
342#[must_use]
343pub fn categorical_kl<const K: usize>(probability: &[f64; K], reference: &[f64; K]) -> f64 {
344    let probability_sum = probability.iter().sum::<f64>();
345    let reference_sum = reference.iter().sum::<f64>();
346    if K == 0
347        || probability
348            .iter()
349            .any(|value| *value < 0.0 || !value.is_finite())
350        || reference
351            .iter()
352            .any(|value| *value <= 0.0 || !value.is_finite())
353        || probability_sum <= 0.0
354        || !probability_sum.is_finite()
355        || !reference_sum.is_finite()
356    {
357        return f64::NAN;
358    }
359
360    let relative: [f64; K] = std::array::from_fn(|category| {
361        let value = probability[category];
362        if value > 0.0 {
363            (reference[category] - value) / value
364        } else {
365            0.0
366        }
367    });
368    let use_series = probability
369        .iter()
370        .zip(relative.iter())
371        .all(|(value, relative)| *value <= 0.0 || relative.abs() <= 0.25);
372    if use_series {
373        let mut powers = relative;
374        let mut sum = 0.0;
375        for order in 1..=128 {
376            let order_f = f64::from(order);
377            let weighted_power = probability
378                .iter()
379                .zip(powers.iter())
380                .map(|(weight, power)| weight * power)
381                .sum::<f64>();
382            let magnitude = probability
383                .iter()
384                .zip(powers.iter())
385                .map(|(weight, power)| weight * power.abs())
386                .sum::<f64>()
387                / order_f;
388            let sign = if order % 2 == 0 { 1.0 } else { -1.0 };
389            sum += sign * weighted_power / order_f;
390            if order > 1 && magnitude <= f64::EPSILON * sum.abs() {
391                break;
392            }
393            for (power, relative) in powers.iter_mut().zip(relative.iter()) {
394                *power *= relative;
395            }
396        }
397        sum
398    } else {
399        probability
400            .iter()
401            .zip(reference)
402            .filter(|(value, _)| **value > 0.0)
403            .map(|(value, reference)| value * (value.ln() - reference.ln()))
404            .sum()
405    }
406}
407
408/// Exponential integral `E1(x) = integral_x^inf exp(-t) / t dt`.
409///
410/// Returns `NaN` for negative or `NaN` inputs, positive infinity at zero, and
411/// zero at positive infinity.
412#[must_use]
413pub fn exponential_integral_e1(x: f64) -> f64 {
414    if x < 0.0 || x.is_nan() {
415        return f64::NAN;
416    }
417    if x == 0.0 {
418        return f64::INFINITY;
419    }
420    if x == f64::INFINITY {
421        return 0.0;
422    }
423
424    if x <= 1.0 {
425        exponential_integral_e1_series(x)
426    } else {
427        exponential_integral_e1_continued_fraction(x)
428    }
429}
430
431#[allow(clippy::cast_precision_loss)]
432fn exponential_integral_e1_series(x: f64) -> f64 {
433    const MAX_ITERATIONS: usize = 1_000;
434    const EPSILON: f64 = 1.0e-16;
435
436    let mut factorial_term = -x;
437    let mut sum = factorial_term;
438    for iteration in 2..=MAX_ITERATIONS {
439        let k = iteration as f64;
440        factorial_term *= -x / k;
441        let term = factorial_term / k;
442        sum += term;
443        if term.abs() <= EPSILON * sum.abs().max(1.0) {
444            break;
445        }
446    }
447
448    -EULER_MASCHERONI - x.ln() - sum
449}
450
451#[allow(clippy::cast_precision_loss)]
452fn exponential_integral_e1_continued_fraction(x: f64) -> f64 {
453    const MAX_ITERATIONS: usize = 1_000;
454    const EPSILON: f64 = 1.0e-14;
455    const TINY: f64 = 1.0e-300;
456
457    let mut b = x + 1.0;
458    let mut c = 1.0 / TINY;
459    let mut d = 1.0 / b;
460    let mut h = d;
461
462    for iteration in 1..=MAX_ITERATIONS {
463        let i = iteration as f64;
464        let a = -(i * i);
465        b += 2.0;
466
467        d = a.mul_add(d, b);
468        if d.abs() < TINY {
469            d = TINY;
470        }
471        c = b + a / c;
472        if c.abs() < TINY {
473            c = TINY;
474        }
475        d = 1.0 / d;
476        let delta = c * d;
477        h *= delta;
478        if (delta - 1.0).abs() <= EPSILON {
479            break;
480        }
481    }
482
483    (-x).exp() * h
484}
485
486/// Standard normal log-density.
487#[must_use]
488#[inline]
489pub fn unit_normal_log_pdf(z: f64) -> f64 {
490    (0.5 * z).mul_add(-z, -HALF_LOG_2_PI)
491}
492
493/// Student-t normalizing constant on the negative log-density scale.
494#[must_use]
495#[inline]
496pub fn student_t_nll_constant(nu: f64) -> f64 {
497    f64::midpoint(nu.ln(), std::f64::consts::PI.ln()) - ln_gamma_delta(0.5 * nu, 0.5)
498}
499
500/// Standard Student-t log-density.
501///
502/// Returns `NaN` for invalid degrees of freedom or a `NaN` variate, and
503/// negative infinity at either infinite tail.
504#[must_use]
505#[inline]
506pub fn student_t_log_pdf_standardized(t: f64, nu: f64) -> f64 {
507    if nu <= 0.0 || !nu.is_finite() || t.is_nan() {
508        return f64::NAN;
509    }
510    if t.is_infinite() {
511        return f64::NEG_INFINITY;
512    }
513
514    -student_t_nll_constant(nu) - f64::midpoint(nu, 1.0) * log_one_plus_square_over_positive(t, nu)
515}
516
517/// Standard Student-t CDF.
518///
519/// Returns `NaN` for invalid degrees of freedom or a `NaN` variate. Infinite
520/// tails map to zero and one.
521#[must_use]
522#[inline]
523pub fn student_t_cdf_standardized(t: f64, nu: f64) -> f64 {
524    student_t_log_cdf_standardized(t, nu).exp()
525}
526
527/// Logarithm of the standard Student-t CDF.
528///
529/// Unlike taking the logarithm of [`student_t_cdf_standardized`], this keeps
530/// finite log-probabilities in the far negative tail after the probability
531/// itself has underflowed.
532#[must_use]
533#[inline]
534pub fn student_t_log_cdf_standardized(t: f64, nu: f64) -> f64 {
535    if nu <= 0.0 || !nu.is_finite() || t.is_nan() {
536        return f64::NAN;
537    }
538    if !t.is_finite() {
539        return if t.is_sign_negative() {
540            f64::NEG_INFINITY
541        } else {
542            0.0
543        };
544    }
545    if t == 0.0 {
546        return -std::f64::consts::LN_2;
547    }
548
549    let log_x = -log_one_plus_square_over_positive(t, nu);
550    let x = log_x.exp();
551    let a = 0.5 * nu;
552    let log_beta = if x == 0.0 {
553        a * log_x - ln_beta(a, 0.5) - a.ln()
554    } else {
555        log_regularized_beta(a, 0.5, x)
556    };
557    if t < 0.0 {
558        log_beta - std::f64::consts::LN_2
559    } else {
560        (-0.5 * log_beta.exp()).ln_1p()
561    }
562}
563
564#[inline]
565fn log_one_plus_square_over_positive(value: f64, positive: f64) -> f64 {
566    let log_ratio = 0.5_f64.mul_add(-positive.ln(), value.abs().ln());
567    if log_ratio <= 0.0 {
568        (2.0 * log_ratio).exp().ln_1p()
569    } else {
570        2.0_f64.mul_add(log_ratio, (-2.0 * log_ratio).exp().ln_1p())
571    }
572}
573
574/// Digamma function approximation for positive arguments.
575#[must_use]
576#[inline]
577pub fn digamma(value: f64) -> f64 {
578    if value <= 0.0 || !value.is_finite() {
579        return f64::NAN;
580    }
581
582    let mut x = value;
583    let mut result = 0.0;
584
585    #[allow(clippy::while_float)]
586    while x < 8.0 {
587        result -= 1.0 / x;
588        x += 1.0;
589    }
590
591    let inv = 1.0 / x;
592    let inv_sq = inv * inv;
593    let inv_fourth = inv_sq * inv_sq;
594    let inv_sixth = inv_fourth * inv_sq;
595    let inv_eighth = inv_fourth * inv_fourth;
596    let inv_tenth = inv_eighth * inv_sq;
597    let inv_twelfth = inv_tenth * inv_sq;
598    0.5f64.mul_add(-inv, result + x.ln()) - inv_sq / 12.0 + inv_fourth / 120.0 - inv_sixth / 252.0
599        + inv_eighth / 240.0
600        - 5.0 * inv_tenth / 660.0
601        + 691.0 * inv_twelfth / 32_760.0
602}
603
604/// Difference `digamma(x) - ln(x)` for positive finite `x`.
605///
606/// The asymptotic form avoids subtracting nearly equal logarithms for large
607/// arguments.
608#[must_use]
609#[inline]
610pub fn digamma_minus_ln(value: f64) -> f64 {
611    if value <= 0.0 || !value.is_finite() {
612        return f64::NAN;
613    }
614    if value < 8.0 {
615        return digamma(value) - value.ln();
616    }
617
618    let inverse = 1.0 / value;
619    let inverse_squared = inverse * inverse;
620    let inverse_fourth = inverse_squared * inverse_squared;
621    let inverse_sixth = inverse_fourth * inverse_squared;
622    let inverse_eighth = inverse_fourth * inverse_fourth;
623    let inverse_tenth = inverse_eighth * inverse_squared;
624    let inverse_twelfth = inverse_tenth * inverse_squared;
625    (-0.5_f64).mul_add(inverse, -inverse_squared / 12.0) + inverse_fourth / 120.0
626        - inverse_sixth / 252.0
627        + inverse_eighth / 240.0
628        - 5.0 * inverse_tenth / 660.0
629        + 691.0 * inverse_twelfth / 32_760.0
630}
631
632/// Difference `digamma(base + increment) - digamma(base)` for positive arguments.
633///
634/// This evaluates the large-argument asymptotic series term by term, avoiding
635/// cancellation when `increment` is smaller than the spacing between nearby
636/// representable values at `base`.
637#[must_use]
638pub fn digamma_delta(base: f64, increment: f64) -> f64 {
639    if base <= 0.0 || increment < 0.0 || !base.is_finite() || !increment.is_finite() {
640        return f64::NAN;
641    }
642    if increment == 0.0 {
643        return 0.0;
644    }
645
646    let target = base + increment;
647    if !target.is_finite() {
648        return f64::INFINITY;
649    }
650    let mut shifted = base;
651    let mut recurrence = 0.0;
652    #[allow(clippy::while_float)]
653    while shifted < 8.0 {
654        let shifted_target = shifted + increment;
655        recurrence += if increment > shifted {
656            (1.0 - shifted / shifted_target) / shifted
657        } else {
658            increment / shifted / shifted_target
659        };
660        shifted += 1.0;
661    }
662
663    let ratio = increment / shifted;
664    let log_ratio = ratio.ln_1p();
665    let inv = 1.0 / shifted;
666    let inv_sq = inv * inv;
667    let inv_fourth = inv_sq * inv_sq;
668    let inv_sixth = inv_fourth * inv_sq;
669    let inv_eighth = inv_fourth * inv_fourth;
670    let inv_tenth = inv_eighth * inv_sq;
671    let inv_twelfth = inv_tenth * inv_sq;
672    let reciprocal_delta = 0.5 * inv * ratio / (1.0 + ratio);
673
674    recurrence + log_ratio + reciprocal_delta - inv_sq * (-2.0 * log_ratio).exp_m1() / 12.0
675        + inv_fourth * (-4.0 * log_ratio).exp_m1() / 120.0
676        - inv_sixth * (-6.0 * log_ratio).exp_m1() / 252.0
677        + inv_eighth * (-8.0 * log_ratio).exp_m1() / 240.0
678        - 5.0 * inv_tenth * (-10.0 * log_ratio).exp_m1() / 660.0
679        + 691.0 * inv_twelfth * (-12.0 * log_ratio).exp_m1() / 32_760.0
680}
681
682/// Regularized incomplete beta function `I_x(a, b)` for positive `a`, `b`.
683#[must_use]
684#[inline]
685pub fn regularized_beta(a: f64, b: f64, x: f64) -> f64 {
686    clamp_probability(regularized_beta_pair_unchecked(a, b, x).0)
687}
688
689/// Complement of the regularized incomplete beta function, `1 - I_x(a, b)`.
690///
691/// This avoids subtracting from one in the upper tail when the continued
692/// fraction can compute the complement directly.
693#[must_use]
694#[inline]
695pub fn regularized_beta_complement(a: f64, b: f64, x: f64) -> f64 {
696    clamp_probability(regularized_beta_pair_unchecked(a, b, x).1)
697}
698
699/// Logarithm of the regularized incomplete beta function `I_x(a, b)`.
700///
701/// The lower-tail branch is evaluated directly in log space so callers can
702/// retain probabilities smaller than the normal floating-point range.
703#[must_use]
704#[inline]
705pub fn log_regularized_beta(a: f64, b: f64, x: f64) -> f64 {
706    if a <= 0.0 || b <= 0.0 || !a.is_finite() || !b.is_finite() || !(0.0..=1.0).contains(&x) {
707        return f64::NAN;
708    }
709    if x == 0.0 {
710        return f64::NEG_INFINITY;
711    }
712    #[allow(clippy::float_cmp)]
713    if x == 1.0 {
714        return 0.0;
715    }
716
717    let log_front = b.mul_add((-x).ln_1p(), a.mul_add(x.ln(), -ln_beta(a, b)));
718    if x < (a + 1.0) / (a + b + 2.0) {
719        log_front + beta_continued_fraction(a, b, x).ln() - a.ln()
720    } else {
721        let log_complement = log_front + beta_continued_fraction(b, a, 1.0 - x).ln() - b.ln();
722        (-log_complement.exp().clamp(0.0, 1.0)).ln_1p()
723    }
724}
725
726#[allow(clippy::suboptimal_flops)]
727fn regularized_beta_pair_unchecked(a: f64, b: f64, x: f64) -> (f64, f64) {
728    if a <= 0.0 || b <= 0.0 || !a.is_finite() || !b.is_finite() || !(0.0..=1.0).contains(&x) {
729        return (f64::NAN, f64::NAN);
730    }
731    if x == 0.0 {
732        return (0.0, 1.0);
733    }
734    #[allow(clippy::float_cmp)]
735    if x == 1.0 {
736        return (1.0, 0.0);
737    }
738
739    let front = beta_front(a, b, x);
740    let term = if x < (a + 1.0) / (a + b + 2.0) {
741        front * beta_continued_fraction(a, b, x) / a
742    } else {
743        front * beta_continued_fraction(b, a, 1.0 - x) / b
744    };
745
746    if x < (a + 1.0) / (a + b + 2.0) {
747        (term, 1.0 - term)
748    } else {
749        (1.0 - term, term)
750    }
751}
752
753#[inline]
754fn beta_front(a: f64, b: f64, x: f64) -> f64 {
755    b.mul_add((-x).ln_1p(), a.mul_add(x.ln(), -ln_beta(a, b)))
756        .exp()
757}
758
759/// Regularized lower incomplete gamma function `P(a, x)`.
760#[must_use]
761#[inline]
762pub fn regularized_gamma_lower(a: f64, x: f64) -> f64 {
763    clamp_probability(regularized_gamma_lower_unchecked(a, x))
764}
765
766/// Regularized upper incomplete gamma function `Q(a, x) = 1 - P(a, x)`.
767#[must_use]
768#[inline]
769pub fn regularized_gamma_upper(a: f64, x: f64) -> f64 {
770    clamp_probability(regularized_gamma_upper_unchecked(a, x))
771}
772
773fn regularized_gamma_lower_unchecked(a: f64, x: f64) -> f64 {
774    if a <= 0.0 || !a.is_finite() || x < 0.0 || !x.is_finite() {
775        return f64::NAN;
776    }
777    if x == 0.0 {
778        return 0.0;
779    }
780
781    if use_gamma_saddlepoint(a, x) {
782        return gamma_saddlepoint_pair(a, x).0;
783    }
784
785    if x < a + 1.0 {
786        gamma_lower_series(a, x)
787    } else {
788        1.0 - gamma_upper_continued_fraction(a, x)
789    }
790}
791
792fn regularized_gamma_upper_unchecked(a: f64, x: f64) -> f64 {
793    if a <= 0.0 || !a.is_finite() || x < 0.0 || !x.is_finite() {
794        return f64::NAN;
795    }
796    if x == 0.0 {
797        return 1.0;
798    }
799
800    if use_gamma_saddlepoint(a, x) {
801        return gamma_saddlepoint_pair(a, x).1;
802    }
803
804    if x < a + 1.0 {
805        1.0 - gamma_lower_series(a, x)
806    } else {
807        gamma_upper_continued_fraction(a, x)
808    }
809}
810
811#[inline]
812fn use_gamma_saddlepoint(a: f64, x: f64) -> bool {
813    const MIN_SHAPE: f64 = 50_000.0;
814    const MAX_CENTERED_DISTANCE: f64 = 10.0;
815
816    a >= MIN_SHAPE && (x - a).abs() <= MAX_CENTERED_DISTANCE * a.sqrt()
817}
818
819fn gamma_saddlepoint_pair(a: f64, x: f64) -> (f64, f64) {
820    let sqrt_a = a.sqrt();
821    let centered = (x - a) / sqrt_a;
822    if centered.abs() <= 1.0e-5 {
823        let central_correction = centered + 1.0 / (3.0 * sqrt_a);
824        let lower = INV_SQRT_2_PI.mul_add(central_correction, 0.5);
825        return (lower, 1.0 - lower);
826    }
827
828    let lambda = x / a;
829    let eta = lambda - 1.0 - lambda.ln();
830    if eta <= 0.0 {
831        return (0.5, 0.5);
832    }
833
834    let r = (2.0 * a * eta).sqrt().copysign(lambda - 1.0);
835    let correction = unit_normal_log_pdf(r).exp() * (1.0 / r - 1.0 / centered);
836    let lower = unit_normal_cdf(r) + correction;
837    (lower, 1.0 - lower)
838}
839
840fn gamma_lower_series(a: f64, x: f64) -> f64 {
841    const MAX_ITERATIONS: usize = 10_000;
842    const EPSILON: f64 = 1.0e-14;
843
844    let mut term = 1.0 / a;
845    let mut sum = term;
846    let mut ap = a;
847    for _ in 0..MAX_ITERATIONS {
848        ap += 1.0;
849        term *= x / ap;
850        sum += term;
851        if term.abs() <= sum.abs() * EPSILON {
852            break;
853        }
854    }
855
856    sum * (a.mul_add(x.ln(), -x) - ln_gamma(a)).exp()
857}
858
859#[allow(clippy::cast_precision_loss)]
860fn gamma_upper_continued_fraction(a: f64, x: f64) -> f64 {
861    const MAX_ITERATIONS: usize = 1_000;
862    const EPSILON: f64 = 1.0e-14;
863    const TINY: f64 = 1.0e-300;
864
865    let mut b = x + 1.0 - a;
866    let mut c = 1.0 / TINY;
867    if b.abs() < TINY {
868        b = TINY;
869    }
870    let mut d = 1.0 / b;
871    let mut h = d;
872
873    for iteration in 1..=MAX_ITERATIONS {
874        let i = iteration as f64;
875        let an = -i * (i - a);
876        b += 2.0;
877        d = an.mul_add(d, b);
878        if d.abs() < TINY {
879            d = TINY;
880        }
881        c = b + an / c;
882        if c.abs() < TINY {
883            c = TINY;
884        }
885        d = 1.0 / d;
886        let delta = d * c;
887        h *= delta;
888        if (delta - 1.0).abs() < EPSILON {
889            break;
890        }
891    }
892
893    (a.mul_add(x.ln(), -x) - ln_gamma(a)).exp() * h
894}
895
896/// Generalized inverse for a discrete CDF on non-negative integer support.
897///
898/// Returns `NaN` when `p` is outside `[0, 1]`, when the supplied CDF returns a
899/// non-finite value, or when `max_count` is reached before the CDF reaches `p`.
900#[must_use]
901#[allow(clippy::cast_precision_loss)]
902pub fn discrete_quantile<F>(p: f64, max_count: u64, mut cdf: F) -> f64
903where
904    F: FnMut(u64) -> f64,
905{
906    if !is_probability(p) {
907        return f64::NAN;
908    }
909    if p == 0.0 {
910        return 0.0;
911    }
912
913    let cdf_zero = cdf(0);
914    if !cdf_zero.is_finite() {
915        return f64::NAN;
916    }
917    if cdf_zero >= p {
918        return 0.0;
919    }
920    if max_count == 0 {
921        return f64::NAN;
922    }
923
924    let mut high = 1_u64.min(max_count);
925    loop {
926        let cdf_high = cdf(high);
927        if !cdf_high.is_finite() {
928            return f64::NAN;
929        }
930        if cdf_high >= p {
931            break;
932        }
933        if high == max_count {
934            return f64::NAN;
935        }
936        high = high.saturating_mul(2).min(max_count);
937    }
938
939    let mut low = 0_u64;
940    while low < high {
941        let mid = low + (high - low) / 2;
942        let cdf_mid = cdf(mid);
943        if !cdf_mid.is_finite() {
944            return f64::NAN;
945        }
946        if cdf_mid < p {
947            low = mid + 1;
948        } else {
949            high = mid;
950        }
951    }
952
953    low as f64
954}
955
956/// Inverts a monotone CDF on a finite closed interval by bisection.
957///
958/// Returns the interval boundary for `p == 0` or `p == 1`, and `NaN` for
959/// invalid probabilities, non-finite bounds, reversed bounds, non-finite CDF
960/// evaluations, or endpoints that do not bracket `p`.
961#[must_use]
962#[allow(clippy::float_cmp)]
963pub fn invert_bounded_cdf<F>(p: f64, lower: f64, upper: f64, mut cdf: F) -> f64
964where
965    F: FnMut(f64) -> f64,
966{
967    if !is_probability(p) || !lower.is_finite() || !upper.is_finite() || lower > upper {
968        return f64::NAN;
969    }
970    if p == 0.0 {
971        return lower;
972    }
973    if p == 1.0 {
974        return upper;
975    }
976
977    let mut low = lower;
978    let mut high = upper;
979    let mut cdf_low = cdf(low);
980    let mut cdf_high = cdf(high);
981    if !cdf_low.is_finite()
982        || !cdf_high.is_finite()
983        || cdf_low > cdf_high
984        || p < cdf_low
985        || p > cdf_high
986    {
987        return f64::NAN;
988    }
989
990    for _ in 0..120 {
991        let mid = low.midpoint(high);
992        let cdf_mid = cdf(mid);
993        if !cdf_mid.is_finite() {
994            return f64::NAN;
995        }
996        if cdf_mid < p {
997            low = mid;
998            cdf_low = cdf_mid;
999        } else {
1000            high = mid;
1001            cdf_high = cdf_mid;
1002        }
1003    }
1004
1005    let mid = low.midpoint(high);
1006    let cdf_mid = cdf(mid);
1007    if !cdf_mid.is_finite() {
1008        return f64::NAN;
1009    }
1010
1011    let low_error = (cdf_low - p).abs();
1012    let mid_error = (cdf_mid - p).abs();
1013    let high_error = (cdf_high - p).abs();
1014    if low_error <= mid_error && low_error <= high_error {
1015        low
1016    } else if high_error <= mid_error {
1017        high
1018    } else {
1019        mid
1020    }
1021}
1022
1023/// Inverts a monotone CDF on `[0, +inf)` by bracketing and bisection.
1024///
1025/// Returns `0` for `p == 0`, `+inf` for `p == 1`, and `NaN` for invalid
1026/// probabilities, non-finite CDF values, or failed finite bracketing for
1027/// interior probabilities.
1028#[must_use]
1029pub fn invert_positive_cdf<F>(p: f64, mut cdf: F) -> f64
1030where
1031    F: FnMut(f64) -> f64,
1032{
1033    if !is_probability(p) {
1034        return f64::NAN;
1035    }
1036    if p == 0.0 {
1037        return 0.0;
1038    }
1039    #[allow(clippy::float_cmp)]
1040    if p == 1.0 {
1041        return f64::INFINITY;
1042    }
1043
1044    let mut high = 1.0;
1045    loop {
1046        let cdf_high = cdf(high);
1047        if !cdf_high.is_finite() {
1048            return f64::NAN;
1049        }
1050        if cdf_high >= p {
1051            break;
1052        }
1053        high *= 2.0;
1054        if !high.is_finite() {
1055            return f64::NAN;
1056        }
1057    }
1058
1059    invert_bounded_cdf(p, 0.0, high, cdf)
1060}
1061
1062/// Inverts a monotone CDF on the real line by bracketing and bisection.
1063///
1064/// Returns infinite tails for boundary probabilities and `NaN` for invalid
1065/// probabilities, non-finite CDF values, or failed finite bracketing for
1066/// interior probabilities.
1067#[must_use]
1068pub fn invert_real_cdf<F>(p: f64, mut cdf: F) -> f64
1069where
1070    F: FnMut(f64) -> f64,
1071{
1072    if !is_probability(p) {
1073        return f64::NAN;
1074    }
1075    if p == 0.0 {
1076        return f64::NEG_INFINITY;
1077    }
1078    #[allow(clippy::float_cmp)]
1079    if p == 1.0 {
1080        return f64::INFINITY;
1081    }
1082
1083    let mut low = -1.0;
1084    loop {
1085        let cdf_low = cdf(low);
1086        if !cdf_low.is_finite() {
1087            return f64::NAN;
1088        }
1089        if cdf_low <= p {
1090            break;
1091        }
1092        low *= 2.0;
1093        if !low.is_finite() {
1094            return f64::NAN;
1095        }
1096    }
1097
1098    let mut high = 1.0;
1099    loop {
1100        let cdf_high = cdf(high);
1101        if !cdf_high.is_finite() {
1102            return f64::NAN;
1103        }
1104        if cdf_high >= p {
1105            break;
1106        }
1107        high *= 2.0;
1108        if !high.is_finite() {
1109            return f64::NAN;
1110        }
1111    }
1112
1113    invert_bounded_cdf(p, low, high, cdf)
1114}
1115
1116/// Integrates a finite interval with adaptive Simpson quadrature.
1117///
1118/// Returns `NaN` for non-finite bounds, reversed bounds, or non-finite function
1119/// evaluations.
1120#[must_use]
1121pub fn integrate_finite<F>(lower: f64, upper: f64, mut function: F) -> f64
1122where
1123    F: FnMut(f64) -> f64,
1124{
1125    const EPSILON: f64 = 1.0e-10;
1126    const MAX_DEPTH: u32 = 24;
1127
1128    if !lower.is_finite() || !upper.is_finite() || lower > upper {
1129        return f64::NAN;
1130    }
1131
1132    #[allow(clippy::float_cmp)]
1133    if lower == upper {
1134        return 0.0;
1135    }
1136
1137    let mid = lower.midpoint(upper);
1138    let f_lower = function(lower);
1139    let f_mid = function(mid);
1140    let f_upper = function(upper);
1141    if !f_lower.is_finite() || !f_mid.is_finite() || !f_upper.is_finite() {
1142        return f64::NAN;
1143    }
1144
1145    let whole = simpson(lower, upper, f_lower, f_mid, f_upper);
1146    adaptive_simpson(
1147        &mut function,
1148        lower,
1149        upper,
1150        [f_lower, f_mid, f_upper],
1151        whole,
1152        EPSILON,
1153        MAX_DEPTH,
1154    )
1155}
1156
1157fn adaptive_simpson<F>(
1158    function: &mut F,
1159    lower: f64,
1160    upper: f64,
1161    values: [f64; 3],
1162    whole: f64,
1163    epsilon: f64,
1164    depth: u32,
1165) -> f64
1166where
1167    F: FnMut(f64) -> f64,
1168{
1169    let [f_lower, f_mid, f_upper] = values;
1170    let mid = lower.midpoint(upper);
1171    let left_mid = lower.midpoint(mid);
1172    let right_mid = mid.midpoint(upper);
1173    let f_left_mid = function(left_mid);
1174    let f_right_mid = function(right_mid);
1175    if !f_left_mid.is_finite() || !f_right_mid.is_finite() {
1176        return f64::NAN;
1177    }
1178
1179    let left = simpson(lower, mid, f_lower, f_left_mid, f_mid);
1180    let right = simpson(mid, upper, f_mid, f_right_mid, f_upper);
1181    let delta = left + right - whole;
1182    if depth == 0 || delta.abs() <= 15.0 * epsilon {
1183        return left + right + delta / 15.0;
1184    }
1185
1186    let left_integral = adaptive_simpson(
1187        function,
1188        lower,
1189        mid,
1190        [f_lower, f_left_mid, f_mid],
1191        left,
1192        0.5 * epsilon,
1193        depth - 1,
1194    );
1195    let right_integral = adaptive_simpson(
1196        function,
1197        mid,
1198        upper,
1199        [f_mid, f_right_mid, f_upper],
1200        right,
1201        0.5 * epsilon,
1202        depth - 1,
1203    );
1204
1205    left_integral + right_integral
1206}
1207
1208#[inline]
1209fn simpson(lower: f64, upper: f64, f_lower: f64, f_mid: f64, f_upper: f64) -> f64 {
1210    (upper - lower) * (4.0f64.mul_add(f_mid, f_lower) + f_upper) / 6.0
1211}
1212
1213#[allow(clippy::cast_precision_loss)]
1214fn beta_continued_fraction(a: f64, b: f64, x: f64) -> f64 {
1215    const MAX_ITERATIONS: usize = 200;
1216    const EPSILON: f64 = 3.0e-14;
1217    const TINY: f64 = 1.0e-300;
1218
1219    let qab = a + b;
1220    let qap = a + 1.0;
1221    let qam = a - 1.0;
1222    let mut c = 1.0;
1223    let mut d = 1.0 - qab * x / qap;
1224    if d.abs() < TINY {
1225        d = TINY;
1226    }
1227    d = 1.0 / d;
1228    let mut h = d;
1229
1230    for iteration in 1..=MAX_ITERATIONS {
1231        let m = iteration as f64;
1232        let m2 = 2.0 * m;
1233
1234        let aa = m * (b - m) * x / ((qam + m2) * (a + m2));
1235        d = 1.0 + aa * d;
1236        if d.abs() < TINY {
1237            d = TINY;
1238        }
1239        c = 1.0 + aa / c;
1240        if c.abs() < TINY {
1241            c = TINY;
1242        }
1243        d = 1.0 / d;
1244        h *= d * c;
1245
1246        let aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));
1247        d = 1.0 + aa * d;
1248        if d.abs() < TINY {
1249            d = TINY;
1250        }
1251        c = 1.0 + aa / c;
1252        if c.abs() < TINY {
1253            c = TINY;
1254        }
1255        d = 1.0 / d;
1256        let delta = d * c;
1257        h *= delta;
1258        if (delta - 1.0).abs() < EPSILON {
1259            break;
1260        }
1261    }
1262
1263    h
1264}
1265
1266/// Standard normal CDF.
1267#[must_use]
1268#[inline]
1269pub fn unit_normal_cdf(z: f64) -> f64 {
1270    unit_normal_sf(-z)
1271}
1272
1273/// Standard normal survival function `1 - Phi(z)`.
1274#[must_use]
1275#[inline]
1276pub fn unit_normal_sf(z: f64) -> f64 {
1277    if z.is_nan() {
1278        return f64::NAN;
1279    }
1280    if z == f64::NEG_INFINITY {
1281        return 1.0;
1282    }
1283    if z == f64::INFINITY {
1284        return 0.0;
1285    }
1286
1287    clamp_probability(0.5 * unit_normal_erfc(z * std::f64::consts::FRAC_1_SQRT_2))
1288}
1289
1290/// Natural logarithm of the standard normal survival function.
1291#[must_use]
1292#[inline]
1293pub fn unit_normal_log_sf(z: f64) -> f64 {
1294    log_ndtr(-z)
1295}
1296
1297fn unit_normal_erfc(x: f64) -> f64 {
1298    const ERF_NUMERATOR: [f64; 5] = [
1299        9.604_973_739_870_516,
1300        90.026_019_720_384_27,
1301        2_232.005_345_946_843,
1302        7_003.325_141_128_051,
1303        55_592.301_301_039_49,
1304    ];
1305    const ERF_DENOMINATOR: [f64; 5] = [
1306        33.561_714_164_750_31,
1307        521.357_949_780_152_7,
1308        4_594.323_829_709_801,
1309        22_629.000_061_389_09,
1310        49_267.394_260_863_59,
1311    ];
1312    const ERFC_NUMERATOR: [f64; 9] = [
1313        2.461_969_814_735_305e-10,
1314        0.564_189_564_831_068_8,
1315        7.463_210_564_422_699,
1316        48.637_197_098_568_14,
1317        196.520_832_956_077_1,
1318        526.445_194_995_477_3,
1319        934.528_527_171_957_6,
1320        1_027.551_886_895_157,
1321        557.535_335_369_399_4,
1322    ];
1323    const ERFC_DENOMINATOR: [f64; 8] = [
1324        13.228_195_115_474_499,
1325        86.707_214_088_598_97,
1326        354.937_778_887_819_9,
1327        975.708_501_743_205_5,
1328        1_823.909_166_879_097_3,
1329        2_246.337_608_187_109_7,
1330        1_656.663_091_941_613_5,
1331        557.535_340_817_727_7,
1332    ];
1333    const ERFC_TAIL_NUMERATOR: [f64; 6] = [
1334        0.564_189_583_547_755_1,
1335        1.275_366_707_599_781,
1336        5.019_050_422_511_805,
1337        6.160_210_979_930_536,
1338        7.409_742_699_504_489,
1339        2.978_866_653_721_002,
1340    ];
1341    const ERFC_TAIL_DENOMINATOR: [f64; 6] = [
1342        2.260_528_632_201_172_6,
1343        9.396_035_249_380_014,
1344        12.048_953_980_809_665,
1345        17.081_445_074_756_59,
1346        9.608_968_090_632_859,
1347        3.369_076_451_000_815,
1348    ];
1349    const SQRT_HALF: f64 = std::f64::consts::FRAC_1_SQRT_2;
1350    const ERFC_UNDERFLOW_X: f64 = 27.3;
1351
1352    if x.abs() <= SQRT_HALF {
1353        let square = x * x;
1354        let erf = x * polynomial_descending(square, &ERF_NUMERATOR)
1355            / polynomial_descending_with_implicit_leading_one(square, &ERF_DENOMINATOR);
1356        return 1.0 - erf;
1357    }
1358
1359    let abs_x = x.abs();
1360    if abs_x >= ERFC_UNDERFLOW_X {
1361        return if x < 0.0 { 2.0 } else { 0.0 };
1362    }
1363
1364    let (numerator, denominator) = if abs_x < 8.0 {
1365        (
1366            polynomial_descending(abs_x, &ERFC_NUMERATOR),
1367            polynomial_descending_with_implicit_leading_one(abs_x, &ERFC_DENOMINATOR),
1368        )
1369    } else {
1370        (
1371            polynomial_descending(abs_x, &ERFC_TAIL_NUMERATOR),
1372            polynomial_descending_with_implicit_leading_one(abs_x, &ERFC_TAIL_DENOMINATOR),
1373        )
1374    };
1375
1376    let erfc = (-abs_x * abs_x).exp() * numerator / denominator;
1377    if x < 0.0 { 2.0 - erfc } else { erfc }
1378}
1379
1380/// Natural logarithm of the standard normal CDF.
1381#[must_use]
1382#[inline]
1383pub fn log_ndtr(z: f64) -> f64 {
1384    if z.is_nan() {
1385        return f64::NAN;
1386    }
1387    if z == f64::NEG_INFINITY {
1388        return f64::NEG_INFINITY;
1389    }
1390    if z == f64::INFINITY {
1391        return 0.0;
1392    }
1393    if z <= -10.0 {
1394        return log_ndtr_left_tail(z);
1395    }
1396    if z > 5.0 {
1397        return (-unit_normal_sf(z)).ln_1p();
1398    }
1399
1400    unit_normal_cdf(z).ln()
1401}
1402
1403fn log_ndtr_left_tail(z: f64) -> f64 {
1404    let x = -z;
1405    let inv2 = 1.0 / (x * x);
1406    let correction = normal_left_tail_correction(inv2);
1407
1408    unit_normal_log_pdf(z) - x.ln() + correction.max(f64::MIN_POSITIVE).ln()
1409}
1410
1411#[inline]
1412fn normal_left_tail_correction(inv2: f64) -> f64 {
1413    polynomial_descending(
1414        inv2,
1415        &[
1416            -34_459_425.0,
1417            2_027_025.0,
1418            -135_135.0,
1419            10_395.0,
1420            -945.0,
1421            105.0,
1422            -15.0,
1423            3.0,
1424            -1.0,
1425            1.0,
1426        ],
1427    )
1428}
1429
1430/// Standard normal Mills ratio `phi(z) / Phi(z)`.
1431///
1432/// Infinite tails map to positive infinity and zero, respectively; `NaN`
1433/// propagates.
1434#[must_use]
1435#[inline]
1436pub fn normal_mills_ratio(z: f64) -> f64 {
1437    if z.is_nan() {
1438        return f64::NAN;
1439    }
1440    if z == f64::NEG_INFINITY {
1441        return f64::INFINITY;
1442    }
1443    if z == f64::INFINITY {
1444        return 0.0;
1445    }
1446
1447    if z <= -10.0 {
1448        let x = -z;
1449        let correction = normal_left_tail_correction(1.0 / (x * x));
1450        return x / correction.max(f64::MIN_POSITIVE);
1451    }
1452
1453    let log_ratio = unit_normal_log_pdf(z) - log_ndtr(z);
1454    if log_ratio.is_nan() && z < 0.0 {
1455        // Both log terms may underflow to `-inf` for extreme finite left-tail
1456        // inputs. The leading asymptotic term remains representable.
1457        -z
1458    } else {
1459        log_ratio.exp()
1460    }
1461}
1462
1463/// Owen's T function `T(h, a)`.
1464///
1465/// This is primarily used for skew-normal CDF evaluation. Arguments with
1466/// `|a| > 1` are reduced by Owen's reciprocal identity, leaving adaptive
1467/// Simpson integration on a bounded interval no wider than one.
1468#[must_use]
1469pub fn owens_t(h: f64, a: f64) -> f64 {
1470    if !h.is_finite() || !a.is_finite() {
1471        return f64::NAN;
1472    }
1473    if a == 0.0 {
1474        return 0.0;
1475    }
1476
1477    let sign = a.signum();
1478    let upper = a.abs();
1479    if upper > 1.0 {
1480        return sign * owens_t_reciprocal_reduction(h.abs(), upper);
1481    }
1482
1483    let h2 = h * h;
1484
1485    #[allow(clippy::suboptimal_flops)]
1486    let integral = integrate_finite(0.0, upper, |x| {
1487        (-0.5 * h2 * (1.0 + x * x)).exp() / (1.0 + x * x)
1488    });
1489    sign * integral / (2.0 * std::f64::consts::PI)
1490}
1491
1492fn owens_t_reciprocal_reduction(h: f64, a: f64) -> f64 {
1493    let scaled_h = h * a;
1494    let cdf_h = unit_normal_cdf(h);
1495    let cdf_scaled = unit_normal_cdf(scaled_h);
1496    let reduced = if scaled_h.is_finite() {
1497        owens_t(scaled_h, 1.0 / a)
1498    } else {
1499        0.0
1500    };
1501    let value = cdf_h.mul_add(-cdf_scaled, f64::midpoint(cdf_h, cdf_scaled)) - reduced;
1502    value.clamp(0.0, 0.25)
1503}
1504
1505/// Standard normal quantile using Wichura's AS241 rational approximation.
1506#[must_use]
1507#[inline]
1508#[allow(clippy::float_cmp)]
1509pub fn unit_normal_quantile(p: f64) -> f64 {
1510    const CENTER_NUMERATOR: [f64; 8] = [
1511        3.387_132_872_796_366_5,
1512        133.141_667_891_784_38,
1513        1_971.590_950_306_551_3,
1514        13_731.693_765_509_46,
1515        45_921.953_931_549_87,
1516        67_265.770_927_008_7,
1517        33_430.575_583_588_13,
1518        2_509.080_928_730_122_7,
1519    ];
1520    const CENTER_DENOMINATOR: [f64; 7] = [
1521        42.313_330_701_600_91,
1522        687.187_007_492_057_9,
1523        5_394.196_021_424_751,
1524        21_213.794_301_586_597,
1525        39_307.895_800_092_71,
1526        28_729.085_735_721_943,
1527        5_226.495_278_852_855,
1528    ];
1529    const TAIL_NUMERATOR: [f64; 8] = [
1530        1.423_437_110_749_683_5,
1531        4.630_337_846_156_545,
1532        5.769_497_221_460_691,
1533        3.647_848_324_763_204_5,
1534        1.270_458_252_452_368_4,
1535        0.241_780_725_177_450_6,
1536        0.022_723_844_989_269_184,
1537        0.000_774_545_014_278_341_4,
1538    ];
1539    const TAIL_DENOMINATOR: [f64; 7] = [
1540        2.053_191_626_637_759,
1541        1.676_384_830_183_803_8,
1542        0.689_767_334_985_1,
1543        0.148_103_976_427_480_08,
1544        0.015_198_666_563_616_457,
1545        0.000_547_593_808_499_534_5,
1546        1.050_750_071_644_416_8e-9,
1547    ];
1548    const FAR_TAIL_NUMERATOR: [f64; 8] = [
1549        6.657_904_643_501_104,
1550        5.463_784_911_164_114,
1551        1.784_826_539_917_291_3,
1552        0.296_560_571_828_504_87,
1553        0.026_532_189_526_576_124,
1554        0.001_242_660_947_388_078_4,
1555        0.000_027_115_555_687_434_876,
1556        0.000_000_201_033_439_929_228_82,
1557    ];
1558    const FAR_TAIL_DENOMINATOR: [f64; 7] = [
1559        0.599_832_206_555_887_9,
1560        0.136_929_880_922_735_8,
1561        0.014_875_361_290_850_615,
1562        0.000_786_869_131_145_613_3,
1563        0.000_018_463_183_175_100_547,
1564        0.000_000_142_151_175_831_644_6,
1565        2.044_263_103_389_939_7e-15,
1566    ];
1567
1568    if p < 0.0 || !p.is_finite() || p > 1.0 {
1569        return f64::NAN;
1570    }
1571    if p == 0.0 {
1572        return f64::NEG_INFINITY;
1573    }
1574    if p == 1.0 {
1575        return f64::INFINITY;
1576    }
1577
1578    let centered = p - 0.5;
1579    if centered.abs() <= 0.425 {
1580        let r = 0.180_625 - centered * centered;
1581        centered * polynomial_ascending(r, &CENTER_NUMERATOR)
1582            / polynomial_ascending_with_constant_one(r, &CENTER_DENOMINATOR)
1583    } else {
1584        let tail_probability = if centered < 0.0 { p } else { 1.0 - p };
1585        let mut r = (-tail_probability.ln()).sqrt();
1586        let quantile = if r <= 5.0 {
1587            r -= 1.6;
1588            polynomial_ascending(r, &TAIL_NUMERATOR)
1589                / polynomial_ascending_with_constant_one(r, &TAIL_DENOMINATOR)
1590        } else {
1591            r -= 5.0;
1592            polynomial_ascending(r, &FAR_TAIL_NUMERATOR)
1593                / polynomial_ascending_with_constant_one(r, &FAR_TAIL_DENOMINATOR)
1594        };
1595        if centered < 0.0 { -quantile } else { quantile }
1596    }
1597}
1598
1599#[cfg(test)]
1600mod tests {
1601    use approx::assert_relative_eq;
1602
1603    use super::{
1604        exponential_integral_e1, log_regularized_beta, regularized_beta,
1605        student_t_cdf_standardized, student_t_log_cdf_standardized, student_t_log_pdf_standardized,
1606    };
1607
1608    #[test]
1609    fn exponential_integral_e1_matches_reference_values() {
1610        assert_relative_eq!(
1611            exponential_integral_e1(0.1),
1612            1.822_923_958_419_390_6,
1613            epsilon = 1.0e-14
1614        );
1615        assert_relative_eq!(
1616            exponential_integral_e1(1.0),
1617            0.219_383_934_395_520_29,
1618            epsilon = 1.0e-14
1619        );
1620        assert_relative_eq!(
1621            exponential_integral_e1(10.0),
1622            0.000_004_156_968_929_685_325,
1623            epsilon = 1.0e-18
1624        );
1625    }
1626
1627    #[test]
1628    fn exponential_integral_e1_handles_invalid_domains() {
1629        assert!(exponential_integral_e1(-1.0).is_nan());
1630        assert!(exponential_integral_e1(f64::NAN).is_nan());
1631        assert!(exponential_integral_e1(0.0).is_infinite());
1632        assert!(exponential_integral_e1(f64::INFINITY).abs() <= f64::EPSILON);
1633    }
1634
1635    #[test]
1636    fn log_regularized_beta_matches_probability_in_regular_range() {
1637        for (a, b, x) in [(0.7, 0.5, 0.01), (2.5, 1.3, 0.4), (4.0, 2.0, 0.9)] {
1638            assert_relative_eq!(
1639                log_regularized_beta(a, b, x),
1640                regularized_beta(a, b, x).ln(),
1641                epsilon = 1.0e-13
1642            );
1643        }
1644    }
1645
1646    #[test]
1647    fn student_t_log_cdf_matches_cdf_and_retains_far_tail() {
1648        for (t, nu) in [(-8.0, 3.0), (-0.7, 5.0), (0.0, 7.0), (2.5, 11.0)] {
1649            assert_relative_eq!(
1650                student_t_log_cdf_standardized(t, nu),
1651                student_t_cdf_standardized(t, nu).ln(),
1652                epsilon = 1.0e-13
1653            );
1654        }
1655        let far_tail = student_t_log_cdf_standardized(-1.0e100, 5.0);
1656        assert!(far_tail.is_finite());
1657        assert!(far_tail < -1_000.0);
1658
1659        let cauchy_tail = student_t_log_cdf_standardized(-1.0e100, 1.0);
1660        let cauchy_asymptotic = 100.0_f64.mul_add(-10.0_f64.ln(), -std::f64::consts::PI.ln());
1661        assert_relative_eq!(cauchy_tail, cauchy_asymptotic, epsilon = 1.0e-12);
1662        assert!(student_t_log_cdf_standardized(0.0, 0.0).is_nan());
1663        assert!(student_t_log_cdf_standardized(f64::NAN, 5.0).is_nan());
1664        let negative_infinity = student_t_log_cdf_standardized(f64::NEG_INFINITY, 5.0);
1665        assert!(negative_infinity.is_infinite() && negative_infinity.is_sign_negative());
1666        assert!(student_t_log_cdf_standardized(f64::INFINITY, 5.0).abs() <= f64::EPSILON);
1667        assert!(student_t_log_pdf_standardized(-1.0e308, 5.0).is_finite());
1668        let small_df_far_tail = student_t_cdf_standardized(-1.0e200, 0.01);
1669        assert!(small_df_far_tail > 0.0);
1670        assert!(small_df_far_tail < 0.5);
1671    }
1672}