xsf/scipy_special/cdflib.rs
1//! Inverses of distribution functions with respect to a parameter, which `scipy.special` computes
2//! with cdflib or Boost, and noncentral distribution functions from cdflib's series. The roots are
3//! found with the bracket search and Chandrupatla solver of [`gdtrib`](crate::gdtrib) to machine
4//! precision, whereas cdflib's `dinvr` stops at a relative tolerance of `1e-10` (`1e-8` for the
5//! noncentral t). If the probability can't be reached, 0 or inf is returned, whichever limit is
6//! closest, instead of cdflib's search bound. If it is 0 or 1, the limit where the CDF is smallest
7//! or largest is returned, instead of a root where the CDF underflows or rounds to it.
8
9use core::f64::consts::{LN_2, SQRT_2};
10
11use crate::ext::quadpack::quad_unimodal;
12use crate::utils::{SQRT_FRAC_2_PI, SQRT_PI, pow2};
13use crate::xsf::cephes::dd_real::{ldexp_f64, two_sum};
14use crate::xsf::cephes::{
15 betainc_xy, fdtr, fdtr_w, igam, igam_exp_scaled, igam_fac, igamc, incbet_cf_factor,
16 incbet_ln_pow_asymp, lbeta, ln_a_beta, ln_gamma_term,
17};
18use crate::xsf::{
19 bracket_root_for_cdf_inversion, erfcx, find_positive_root, find_root_chandrupatla, log1pmx,
20};
21
22/// Inverse of [`stdtr`](crate::stdtr) with respect to `nu`
23///
24/// Corresponds to [`scipy.special.stdtridf`][stdtridf].
25///
26/// [stdtridf]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.stdtridf.html
27///
28/// # See also
29/// - [`stdtr`](crate::stdtr): Student's t distribution CDF
30/// - [`stdtri`](crate::stdtri): Inverse of [`stdtr`](crate::stdtr) with respect to `x`
31#[must_use]
32pub fn stdtridf(p: f64, t: f64) -> f64 {
33 // stdtr(df, t) is 1/2 if t = 0, and 1 or 0 if t = +-inf, independent of df
34 if !((0.0..=1.0).contains(&p) && t != 0.0 && t.is_finite()) {
35 return f64::NAN;
36 }
37 // stdtr(df, -t) = 1 - stdtr(df, t) is used for the upper tail
38 let func = cdf_minus_p(p, |df| crate::stdtr(df, t), |df| crate::stdtr(df, -t));
39 // stdtr(df, t) increases from 1/2 at df = 0 to ndtr(t) at df = inf if t > 0
40 limit_if_p_is_0_or_1(p, t > 0.0).unwrap_or_else(|| find_df_root(func, t > 0.0))
41}
42
43/// Inverse of [`fdtr`](crate::fdtr) with respect to `b`
44///
45/// Corresponds to [`scipy.special.fdtridfd`][fdtridfd].
46///
47/// For `f < 1`, `fdtr` can peak in `b`, so that there can be two roots, of which one is returned.
48/// The same goes for [`ncfdtridfd`] and [`ncfdtridfn`].
49///
50/// [fdtridfd]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.fdtridfd.html
51///
52/// # See also
53/// - [`fdtr`](crate::fdtr): F distribution CDF
54/// - [`fdtri`](crate::fdtri): Inverse of [`fdtr`](crate::fdtr) with respect to `x`
55#[must_use]
56pub fn fdtridfd(dfn: f64, p: f64, f: f64) -> f64 {
57 // fdtr(dfn, dfd, f) is 0 or 1 if f = 0 or inf, independent of dfd
58 if !(dfn > 0.0 && (0.0..=1.0).contains(&p) && is_pos_finite(f)) {
59 return f64::NAN;
60 }
61 let func = cdf_minus_p(
62 p,
63 |dfd| crate::fdtr(dfn, dfd, f),
64 |dfd| crate::fdtrc(dfn, dfd, f),
65 );
66 // fdtr(dfn, dfd, f) goes from 0 at dfd = 0 to chdtr(dfn, dfn f) at dfd = inf
67 limit_if_p_is_0_or_1(p, true).unwrap_or_else(|| find_df_root(func, true))
68}
69
70/// Inverse of [`bdtr`](crate::bdtr) with respect to `k`
71///
72/// Corresponds to [`scipy.special.bdtrik`][bdtrik].
73///
74/// The CDF $\I_{1-p}(n - k, k + 1)$ is continuous in `k`, so that `k` is real. If `y` lies below
75/// the CDF at $k = 0$, i.e. $(1 - p)^n$, 0 is returned.
76///
77/// [bdtrik]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.bdtrik.html
78///
79/// # See also
80/// - [`bdtr`](crate::bdtr): Binomial distribution function
81/// - [`bdtri`](crate::bdtri): Inverse of [`bdtr`](crate::bdtr) with respect to `p`
82/// - [`bdtrin`]: Inverse of [`bdtr`](crate::bdtr) with respect to `n`
83#[must_use]
84pub fn bdtrik(y: f64, n: f64, p: f64) -> f64 {
85 if !((0.0..=1.0).contains(&y) && (0.0..f64::INFINITY).contains(&n) && (0.0..=1.0).contains(&p))
86 {
87 return f64::NAN;
88 }
89 // the CDF is 0 below k = n if p = 1
90 if y > 0.0 && (y == 1.0 || p == 1.0) {
91 return n;
92 }
93 // The CDF `betaincc(k + 1, n - k, p)` increases from (1 - p)^n at k = 0 to 1 at k = n, beyond
94 // which it stays 1.
95 invert_betainc(y, true, n, 1.0 - p, p, |k| ((n - k).max(0.0), k + 1.0))
96}
97
98/// Inverse of [`bdtr`](crate::bdtr) with respect to `n`
99///
100/// Corresponds to [`scipy.special.bdtrin`][bdtrin].
101///
102/// The CDF $\I_{1-p}(n - k, k + 1)$ is continuous in `n`, so that `n` is real.
103///
104/// [bdtrin]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.bdtrin.html
105///
106/// # See also
107/// - [`bdtr`](crate::bdtr): Binomial distribution function
108/// - [`bdtri`](crate::bdtri): Inverse of [`bdtr`](crate::bdtr) with respect to `p`
109/// - [`bdtrik`]: Inverse of [`bdtr`](crate::bdtr) with respect to `k`
110#[must_use]
111pub fn bdtrin(k: f64, y: f64, p: f64) -> f64 {
112 // As in SciPy, NaN if p is 0 or 1, where the CDF is 1 or 0 for all n > k, unless y is 0 or 1,
113 // which give the limits n = inf and n = k.
114 let p_is_valid = p > 0.0 && p < 1.0 || (p == 0.0 || p == 1.0) && (y == 0.0 || y == 1.0);
115 if !((0.0..f64::INFINITY).contains(&k) && (0.0..=1.0).contains(&y) && p_is_valid) {
116 return f64::NAN;
117 }
118 // The CDF `betaincc(k + 1, n - k, p)` decreases from 1 at n = k to 0 at n = inf. It is solved
119 // for `n - k`, which keeps its precision if `n` is close to `k`.
120 k + invert_betainc(y, false, f64::MAX, 1.0 - p, p, |nk| (nk, k + 1.0))
121}
122
123/// Inverse of [`betainc`](crate::betainc) with respect to `a`
124///
125/// Corresponds to [`scipy.special.btdtria`][btdtria].
126///
127/// Unlike in SciPy, NaN is returned for `x > 1` even if `p` is 0 or 1, instead of the limit.
128///
129/// [btdtria]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.btdtria.html
130///
131/// # See also
132/// - [`betainc`](crate::betainc): Regularized incomplete beta function
133/// - [`betaincinv`](crate::betaincinv): Inverse of [`betainc`](crate::betainc) with respect to `x`
134/// - [`btdtrib`]: Inverse of [`betainc`](crate::betainc) with respect to `b`
135#[must_use]
136pub fn btdtria(p: f64, b: f64, x: f64) -> f64 {
137 if !btdtr_is_valid(p, b, x) {
138 return f64::NAN;
139 }
140 // the CDF decreases from 1 at a = 0 to 0 at a = inf
141 invert_betainc(p, false, f64::MAX, x, 1.0 - x, |a| (a, b))
142}
143
144/// Inverse of [`betainc`](crate::betainc) with respect to `b`
145///
146/// Corresponds to [`scipy.special.btdtrib`][btdtrib].
147///
148/// Unlike in SciPy, NaN is returned for `x > 1` even if `p` is 0 or 1, instead of the limit.
149///
150/// [btdtrib]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.btdtrib.html
151///
152/// # See also
153/// - [`betainc`](crate::betainc): Regularized incomplete beta function
154/// - [`betaincinv`](crate::betaincinv): Inverse of [`betainc`](crate::betainc) with respect to `x`
155/// - [`btdtria`]: Inverse of [`betainc`](crate::betainc) with respect to `a`
156#[must_use]
157pub fn btdtrib(a: f64, p: f64, x: f64) -> f64 {
158 if !btdtr_is_valid(p, a, x) {
159 return f64::NAN;
160 }
161 // the CDF increases from 0 at b = 0 to 1 at b = inf
162 invert_betainc(p, true, f64::MAX, x, 1.0 - x, |b| (a, b))
163}
164
165/// Whether `p`, the other shape and `x` are valid arguments of [`btdtria`] and [`btdtrib`]. As in
166/// SciPy, the limits are also returned for `p` = 0 or 1 if the other shape is inf or `x = 1`, where
167/// the CDF doesn't depend on the shape that is solved for.
168fn btdtr_is_valid(p: f64, shape: f64, x: f64) -> bool {
169 let is_limit = p == 0.0 || p == 1.0;
170 (0.0..=1.0).contains(&p)
171 && shape > 0.0
172 && x > 0.0
173 && x <= 1.0
174 && (is_limit || shape.is_finite() && x < 1.0)
175}
176
177/// Inverse of [`chdtr`](crate::chdtr) with respect to `v`
178///
179/// Corresponds to [`scipy.special.chdtriv`][chdtriv].
180///
181/// [chdtriv]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chdtriv.html
182///
183/// # See also
184/// - [`chdtr`](crate::chdtr): Chi-squared distribution function
185/// - [`chdtri`](crate::chdtri): Inverse of [`chdtrc`](crate::chdtrc) with respect to `x`
186/// - [`gdtrib`](crate::gdtrib): Inverse of [`gdtr`](crate::gdtr) with respect to `b`
187#[must_use]
188pub fn chdtriv(p: f64, x: f64) -> f64 {
189 if !(x > 0.0) {
190 return f64::NAN;
191 }
192 // chdtr(v, x) = gdtr(1/2, v/2, x) decreases from 1 at v = 0 to 0 at v = inf, also if x = inf
193 limit_if_p_is_0_or_1(p, false).unwrap_or_else(|| {
194 // as in SciPy, NaN if x/2 underflows to 0, where the CDF would be 0 for all v
195 if 0.5 * x == 0.0 {
196 return f64::NAN;
197 }
198 2.0 * crate::gdtrib(0.5, p, x)
199 })
200}
201
202/// Inverse of [`nbdtr`](crate::nbdtr) with respect to `k`
203///
204/// Corresponds to [`scipy.special.nbdtrik`][nbdtrik].
205///
206/// The CDF $\I_p(n, k + 1)$ is continuous in `k`, so that `k` is real. If `y` lies below the CDF at
207/// $k = 0$, i.e. $p^n$, 0 is returned.
208///
209/// [nbdtrik]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.nbdtrik.html
210///
211/// # See also
212/// - [`nbdtr`](crate::nbdtr): Negative binomial distribution function
213/// - [`nbdtri`](crate::nbdtri): Inverse of [`nbdtr`](crate::nbdtr) with respect to `p`
214/// - [`nbdtrin`]: Inverse of [`nbdtr`](crate::nbdtr) with respect to `n`
215#[must_use]
216pub fn nbdtrik(y: f64, n: f64, p: f64) -> f64 {
217 if !((0.0..=1.0).contains(&y) && is_pos_finite(n) && (0.0..=1.0).contains(&p)) {
218 return f64::NAN;
219 }
220 // the CDF increases from p^n at k = 0 to 1 at k = inf
221 invert_betainc(y, true, f64::MAX, p, 1.0 - p, |k| (n, k + 1.0))
222}
223
224/// Inverse of [`nbdtr`](crate::nbdtr) with respect to `n`
225///
226/// Corresponds to [`scipy.special.nbdtrin`][nbdtrin].
227///
228/// The CDF $\I_p(n, k + 1)$ is continuous in `n`, so that `n` is real. Unlike in SciPy, the limits
229/// inf and 0 are returned if `y` is 0 or 1, instead of NaN. As in SciPy, NaN is returned if `p` is
230/// 0 or 1.
231///
232/// [nbdtrin]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.nbdtrin.html
233///
234/// # See also
235/// - [`nbdtr`](crate::nbdtr): Negative binomial distribution function
236/// - [`nbdtri`](crate::nbdtri): Inverse of [`nbdtr`](crate::nbdtr) with respect to `p`
237/// - [`nbdtrik`]: Inverse of [`nbdtr`](crate::nbdtr) with respect to `k`
238#[must_use]
239pub fn nbdtrin(k: f64, y: f64, p: f64) -> f64 {
240 // NaN if p is 0 or 1, where the CDF is 0 or 1 for all n > 0
241 if !((0.0..f64::INFINITY).contains(&k) && (0.0..=1.0).contains(&y) && p > 0.0 && p < 1.0) {
242 return f64::NAN;
243 }
244 // Unlike in SciPy, the root is found for n, instead of for n + k, which loses n if k >> n.
245 // The CDF decreases from 1 at n = 0 to 0 at n = inf.
246 invert_betainc(y, false, f64::MAX, p, 1.0 - p, |n| (n, k + 1.0))
247}
248
249/// Inverse of [`pdtr`](crate::pdtr) with respect to `k`
250///
251/// Corresponds to [`scipy.special.pdtrik`][pdtrik].
252///
253/// The CDF $Q(k + 1, m)$ is continuous in `k`, so that `k` is real. If `p` lies below the CDF at
254/// $k = 0$, i.e. $e^{-m}$, 0 is returned. As in SciPy, NaN is returned if $p = 1$.
255///
256/// [pdtrik]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.pdtrik.html
257///
258/// # See also
259/// - [`pdtr`](crate::pdtr): Poisson distribution function
260/// - [`pdtri`](crate::pdtri): Inverse of [`pdtr`](crate::pdtr) with respect to `m`
261#[must_use]
262pub fn pdtrik(p: f64, m: f64) -> f64 {
263 // as in SciPy, 0 if p = 0, also if m = inf
264 if !((0.0..1.0).contains(&p) && m >= 0.0 && (m.is_finite() || p == 0.0)) {
265 return f64::NAN;
266 }
267 // the CDF increases from exp(-m) at k = 0 to 1 at k = inf
268 invert_cdf(
269 p,
270 true,
271 f64::MAX,
272 |k| igamc(k + 1.0, m),
273 |k| igam(k + 1.0, m),
274 )
275}
276
277/// `cdf(x) - p`, which is computed as `(1 - p) - sf(x)` with the survival function `sf` if
278/// `p > 1/2`, where `1 - p` is exact, so that the root keeps the precision of the smaller tail.
279fn cdf_minus_p(p: f64, cdf: impl Fn(f64) -> f64, sf: impl Fn(f64) -> f64) -> impl Fn(f64) -> f64 {
280 let q = 1.0 - p;
281 move |x| if p <= q { cdf(x) - p } else { q - sf(x) }
282}
283
284/// 0 or inf, wherever a CDF that is `increasing` in its parameter is smallest if `p = 0`, or
285/// largest if `p = 1`.
286fn limit_if_p_is_0_or_1(p: f64, increasing: bool) -> Option<f64> {
287 (p == 0.0 || p == 1.0).then_some(if (p == 0.0) == increasing {
288 0.0
289 } else {
290 f64::INFINITY
291 })
292}
293
294/// The root in `[MIN_POSITIVE, upper]` of `cdf(x) = p`, with the survival function `sf`, for a CDF
295/// that is `increasing` in `x`, or the limit if `p` is 0 or 1
296fn invert_cdf(
297 p: f64,
298 increasing: bool,
299 upper: f64,
300 cdf: impl Fn(f64) -> f64,
301 sf: impl Fn(f64) -> f64,
302) -> f64 {
303 limit_if_p_is_0_or_1(p, increasing).unwrap_or_else(|| {
304 find_positive_root(
305 cdf_minus_p(p, cdf, sf),
306 f64::MIN_POSITIVE,
307 upper,
308 increasing,
309 )
310 })
311}
312
313/// [`invert_cdf`] of `betainc(a, b, x)`, with `(a, b) = ab(v)`, given `y = 1 - x`, so that the CDF
314/// can also be a complement `betaincc(b, a, y)`, by swapping `x` and `y`
315fn invert_betainc(
316 p: f64,
317 increasing: bool,
318 upper: f64,
319 x: f64,
320 y: f64,
321 ab: impl Fn(f64) -> (f64, f64),
322) -> f64 {
323 let cdf = |v| {
324 let (a, b) = ab(v);
325 betainc_xy(a, b, x, y)
326 };
327 let sf = |v| {
328 let (a, b) = ab(v);
329 betainc_xy(b, a, y, x)
330 };
331 invert_cdf(p, increasing, upper, cdf, sf)
332}
333
334/// The degrees of freedom are searched for in `[8^-DF_K, 8^DF_K] ~ [5e-100, 2e99]`, like in cdflib
335/// from `1e-100`, instead of in all of `f64`, which saves ~460 evaluations of the CDF if `p` can't
336/// be reached.
337const DF_K: i32 = 110;
338
339/// [`find_positive_root`], also searching the other way from the start (1) if `func` doesn't
340/// change sign in the given direction, and then around the extremum of `func` with
341/// [`find_extremum_root`].
342///
343/// The CDFs need not be monotonic in the degrees of freedom: e.g. `fdtr(dfn, dfd, f)` can peak in
344/// `dfd` if `f < 1`, so that if `p` lies above its limit at `dfd = inf`, there can be two roots.
345fn find_df_root(func: impl Fn(f64) -> f64, increasing: bool) -> f64 {
346 let (lower, upper) = (8f64.powi(-DF_K), 8f64.powi(DF_K));
347 let x = find_positive_root(&func, lower, upper, increasing);
348 if x == 0.0 || x == f64::INFINITY {
349 let x_other = find_positive_root(&func, lower, upper, !increasing);
350 if x_other > 0.0 && x_other < f64::INFINITY {
351 return x_other;
352 }
353 return scan_same_sign(&func)
354 .and_then(|points| find_extremum_root(&func, &points, increasing))
355 .unwrap_or(x);
356 }
357 x
358}
359
360/// The number of search points below 1 over which [`scan_same_sign`] needs `func` to stay constant
361/// to assume that it reached its limit, since the CDFs can also round to a constant before a peak
362/// at small `df`, e.g. the noncentral t CDF with `t > 0` between `df = 1` and its peak at
363/// `df ~ 1 / nc^2`, which `8^14 > 1e12` spans for `|nc| <= 1e6`.
364const PLATEAU_K: i32 = 14;
365
366/// `(k, func(8^k))` at the search points `8^k` of [`find_df_root`] from 1 outwards, until `func`
367/// reaches its limits, i.e. stops changing, if `func` has the same sign at all of them.
368fn scan_same_sign(func: impl Fn(f64) -> f64) -> Option<Vec<(i32, f64)>> {
369 let mut points = vec![(0, func(1.0))];
370 for step in [-1, 1] {
371 let mut y_prev = points[0].1;
372 let mut plateau = 0;
373 let mut k = step;
374 while (-DF_K..=DF_K).contains(&k) {
375 let yk = func(8f64.powi(k));
376 points.push((k, yk));
377 plateau = if yk == y_prev { plateau + 1 } else { 0 };
378 if plateau == if step < 0 { PLATEAU_K } else { 1 } {
379 break;
380 }
381 y_prev = yk;
382 k += step;
383 }
384 }
385 points.sort_by_key(|&(k, _)| k);
386 let sign = points[0].1.signum();
387 points
388 .iter()
389 .all(|&(_, y)| y != 0.0 && y.signum() == sign)
390 .then_some(points)
391}
392
393/// Root of `func` next to its extremum, if it has the same sign at all `points` of
394/// [`scan_same_sign`], but the opposite sign at an extremum between them. Of the two roots, the
395/// one where `func` is `increasing` is returned.
396fn find_extremum_root(
397 func: impl Fn(f64) -> f64,
398 points: &[(i32, f64)],
399 increasing: bool,
400) -> Option<f64> {
401 // `sign * func`, which is positive at the points, and negative at the root's extremum
402 let sign = points[0].1.signum();
403 let g = |x: f64| sign * func(x);
404 let gs: Vec<f64> = points.iter().map(|&(_, y)| sign * y).collect();
405 // the smallest local minimum, which is bracketed by its neighbors, unless it's rounding noise
406 let below = |i: usize, j: usize| gs[i] < (1.0 - 8.0 * f64::EPSILON) * gs[j];
407 let i = (1..gs.len() - 1)
408 .filter(|&i| below(i, i - 1) && below(i, i + 1))
409 .min_by(|&i, &j| gs[i].total_cmp(&gs[j]))?;
410 let (xl, xr) = (8f64.powi(points[i - 1].0), 8f64.powi(points[i + 1].0));
411
412 // Golden-section search for the minimum of `g` in `ln x`, until `g` is negative. 100 steps
413 // shrink the interval by `0.618^100 ~ 1e-21`, below the spacing of `ln x`.
414 let inv_phi = (5f64.sqrt() - 1.0) / 2.0;
415 let (mut a, mut b) = (xl.ln(), xr.ln());
416 let (mut c, mut d) = (b - inv_phi * (b - a), a + inv_phi * (b - a));
417 let (mut gc, mut gd) = (g(c.exp()), g(d.exp()));
418 for _ in 0..100 {
419 if !(gc >= 0.0 && gd >= 0.0) {
420 break;
421 }
422 if gc < gd {
423 (b, d, gd) = (d, c, gc);
424 c = b - inv_phi * (b - a);
425 gc = g(c.exp());
426 } else {
427 (a, c, gc) = (c, d, gd);
428 d = a + inv_phi * (b - a);
429 gd = g(d.exp());
430 }
431 }
432 let xm = if gc < 0.0 {
433 c.exp()
434 } else if gd < 0.0 {
435 d.exp()
436 } else {
437 return None;
438 };
439
440 // `func` increases from the search points to the extremum if it's negative there
441 let (x1, x2) = if increasing == (sign < 0.0) {
442 (xl, xm)
443 } else {
444 (xm, xr)
445 };
446 // only a relative tolerance, as in `find_positive_root`
447 let (x, status) =
448 find_root_chandrupatla(&func, x1, x2, func(x1), func(x2), f64::EPSILON, 0.0, 100);
449 (status == 0).then_some(x)
450}
451
452/// The largest noncentrality for [`cumchn`] and [`cumfnc`]: as in cdflib, where `nc / 2` must fit
453/// an `int`, since they sum `~17 sqrt(nc)` terms.
454const NC_MAX: f64 = 2.0 * i32::MAX as f64;
455
456/// Whether `x` is positive and finite
457fn is_pos_finite(x: f64) -> bool {
458 x > 0.0 && x < f64::INFINITY
459}
460
461/// The exponent of the largest power of 2 by which [`rescale`] divides at once.
462const RESCALE: i32 = 500;
463
464/// `ln(x^a y^b / (a B(a, b)))`, with `y = 1 - x`, i.e. `ln(I_x(a, b) - I_x(a + 1, b))`
465/// (A&S 26.5.16), and whether it avoids the cancellation of `lbeta(a, b)`
466fn ln_beta_term(a: f64, b: f64, x: f64, y: f64, lnx: f64, lny: f64) -> (f64, bool) {
467 // Unlike in cdflib, the limit if `a = dfn / 2` rounds to 0, as `a B(a, b) -> 1`
468 if a == 0.0 {
469 return (b * lny, false);
470 }
471 let t = -lbeta(a, b) - a.ln() + a * lnx + b * lny;
472 // Unlike in cdflib, without the cancellation of `lbeta(a, b)` against `a ln(x)` or `b ln(y)`
473 // for a huge `b` or `a`, like the `I_x(a, b)` that the terms start from, if `x` or `y` is
474 // normal (a subnormal one is rounded here)
475 let ln_pow = |p, q, v: f64| incbet_ln_pow_asymp(p, q, v, t).filter(|_| v >= f64::MIN_POSITIVE);
476 if let Some(p) = ln_pow(a, b, x) {
477 (p - a.ln() + b * lny, true)
478 } else if let Some(p) = ln_pow(b, a, y) {
479 (p - a.ln() + a * lnx, true)
480 } else {
481 (t, false)
482 }
483}
484
485/// `(m, k)` with `I_x(a, b) = m 2^k`, where `m ~ 1` and `k < 0` if `I_x(a, b)` underflows, so that
486/// the terms of a series that starts there can be carried as multiples of `2^k`
487fn betainc_scaled(a: f64, b: f64, x: f64, y: f64, lnx: f64, lny: f64) -> (f64, i32) {
488 let ix = betainc_xy(a, b, x, y);
489 if ix >= f64::MIN_POSITIVE {
490 return (ix, 0);
491 }
492 let (ln_term, _) = ln_beta_term(a, b, x, y, lnx, lny);
493 if !ln_term.is_finite() {
494 return (ix, 0);
495 }
496 // I_x(a, b) = x^a y^b / (a B(a, b)) w, with x below the mean if I_x underflows
497 let (w, _) = incbet_cf_factor(a, b, x, y);
498 if !(w > 0.0 && w.is_finite()) {
499 return (ix, 0);
500 }
501 scaled_exp(ln_term, w)
502}
503
504/// `(m, k)` with `exp(ln_term) w = m 2^k` and `m ~ 1`
505fn scaled_exp(ln_term: f64, w: f64) -> (f64, i32) {
506 let k = ((ln_term + w.ln()) / LN_2).round() as i32;
507 ((ln_term - f64::from(k) * LN_2).exp() * w, k)
508}
509
510/// `(m, k)` with `P(a, x) = m 2^k`, as [`betainc_scaled`] for `I_x(a, b)`
511fn igam_scaled(a: f64, x: f64) -> (f64, i32) {
512 let p = igam(a, x);
513 if p >= f64::MIN_POSITIVE {
514 return (p, 0);
515 }
516 igam_exp_scaled(a, x).map_or((p, 0), |(m, ln_f)| scaled_exp(ln_f, m))
517}
518
519/// Divides the `values` by powers of 2, adding their exponents to `scale`, while
520/// `peak * num / den > 2^RESCALE` and `scale < 0`, so that the scaled terms stay finite and below
521/// their unscaled values. Returns the sum of the exponents.
522///
523/// `num / den` is separate, as it can overflow.
524fn rescale(mut peak: f64, num: f64, den: f64, scale: &mut i32, values: &mut [&mut f64]) -> i32 {
525 let mut shift = 0;
526 while *scale < 0 && peak * num > pow2(RESCALE) * den {
527 let k = RESCALE.min(-*scale);
528 peak *= pow2(-k);
529 for v in values.iter_mut() {
530 **v *= pow2(-k);
531 }
532 *scale += k;
533 shift += k;
534 }
535 shift
536}
537
538/// `lambda^k exp(-lambda) / k!` for `k >= 1`
539fn poisson_weight(k: f64, lambda: f64) -> f64 {
540 // `igam_fac` loses `~|ln(lambda)| eps` if lambda < 1
541 if k == 1.0 {
542 lambda * (-lambda).exp()
543 } else {
544 igam_fac(k + 1.0, lambda) / lambda
545 }
546}
547
548/// CDF of the noncentral chi-square distribution
549///
550/// Corresponds to [`scipy.special.chndtr`][chndtr].
551///
552/// [chndtr]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chndtr.html
553///
554/// # See also
555/// - [`chdtr`](crate::chdtr): CDF of the (central) chi-square distribution
556/// - [`chndtri`]: Inverse of [`chndtr`] with respect to `x`
557/// - [`chndtridf`]: Inverse of [`chndtr`] with respect to `df`
558/// - [`chndtrinc`]: Inverse of [`chndtr`] with respect to `nc`
559#[must_use]
560pub fn chndtr(x: f64, df: f64, nc: f64) -> f64 {
561 // the edge cases of SciPy
562 if !(x >= 0.0 && df >= 0.0 && nc >= 0.0) {
563 f64::NAN
564 } else if nc == 0.0 && (df == 0.0 || x.is_infinite()) {
565 1.0
566 } else if nc == 0.0 && df.is_infinite() {
567 0.0
568 } else if df == 0.0 || df.is_infinite() && nc.is_finite() {
569 f64::NAN
570 } else if nc.is_infinite() {
571 if x.is_infinite() { f64::NAN } else { 0.0 }
572 } else if x.is_infinite() {
573 1.0
574 } else if nc > NC_MAX {
575 f64::NAN
576 } else {
577 // Unlike in SciPy, cdflib's series (A&S 26.4.25), as Boost's returns 0 where its central
578 // term underflows, e.g. `chndtr(20, 63.5, 774) = 1.9e-147`.
579 let p = cumchn(x, df, nc);
580 // the rounding of the sum can exceed 1, but keep NaN
581 if p > 1.0 { 1.0 } else { p }
582 }
583}
584
585/// Inverse of [`chndtr`] with respect to `x`
586///
587/// Corresponds to [`scipy.special.chndtrix`][chndtrix].
588///
589/// [chndtrix]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chndtrix.html
590///
591/// # See also
592/// - [`chndtridf`]: Inverse of [`chndtr`] with respect to `df`
593/// - [`chndtrinc`]: Inverse of [`chndtr`] with respect to `nc`
594#[must_use]
595pub fn chndtri(p: f64, df: f64, nc: f64) -> f64 {
596 if !((0.0..=1.0).contains(&p) && is_pos_finite(df) && (0.0..=NC_MAX).contains(&nc)) {
597 return f64::NAN;
598 }
599 limit_if_p_is_0_or_1(p, true).unwrap_or_else(|| {
600 // as low as the smallest subnormal, where `cumchn` is accurate too
601 find_positive_root(|x| cumchn(x, df, nc) - p, f64::from_bits(1), f64::MAX, true)
602 })
603}
604
605/// Inverse of [`chndtr`] with respect to `df`
606///
607/// Corresponds to [`scipy.special.chndtridf`][chndtridf].
608///
609/// [chndtridf]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chndtridf.html
610///
611/// # See also
612/// - [`chndtri`]: Inverse of [`chndtr`] with respect to `x`
613/// - [`chndtrinc`]: Inverse of [`chndtr`] with respect to `nc`
614#[must_use]
615pub fn chndtridf(x: f64, p: f64, nc: f64) -> f64 {
616 if !(is_pos_finite(x) && (0.0..=1.0).contains(&p) && (0.0..=NC_MAX).contains(&nc)) {
617 return f64::NAN;
618 }
619 // the CDF decreases in df
620 limit_if_p_is_0_or_1(p, false)
621 .unwrap_or_else(|| find_df_root(|df| cumchn(x, df, nc) - p, false))
622}
623
624/// Inverse of [`chndtr`] with respect to `nc`
625///
626/// Corresponds to [`scipy.special.chndtrinc`][chndtrinc].
627///
628/// [chndtrinc]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.chndtrinc.html
629///
630/// # See also
631/// - [`chndtri`]: Inverse of [`chndtr`] with respect to `x`
632/// - [`chndtridf`]: Inverse of [`chndtr`] with respect to `df`
633#[must_use]
634pub fn chndtrinc(x: f64, df: f64, p: f64) -> f64 {
635 if !(is_pos_finite(x) && is_pos_finite(df) && (0.0..=1.0).contains(&p)) {
636 return f64::NAN;
637 }
638 // the CDF decreases in nc, from chdtr(df, x) at nc = 0
639 limit_if_p_is_0_or_1(p, false).unwrap_or_else(|| {
640 find_positive_root(|nc| cumchn(x, df, nc) - p, f64::MIN_POSITIVE, NC_MAX, false)
641 })
642}
643
644/// CDF of the noncentral chi-square distribution, from cdflib's `cumchn`.
645///
646/// It sums the series A&S 26.4.25 backward and forward from the term with the largest Poisson
647/// weight, with the incomplete gamma functions from the recurrence A&S 6.5.21.
648///
649/// Unlike in cdflib, as in [`cumfnc`], with `ln_igam_fac` for the first terms of the recurrence,
650/// since the `lgam` differences lose `~a ln(a) eps`, and `igam` instead of `cumchi`.
651fn cumchn(x: f64, df: f64, pnonc: f64) -> f64 {
652 let eps = f64::EPSILON;
653
654 if !(x > 0.0) {
655 return 0.0;
656 }
657 if !(pnonc >= 2.0 * f64::MIN_POSITIVE) {
658 return crate::chdtr(df, x);
659 }
660
661 let xnonc = pnonc / 2.0;
662 // Unlike in cdflib, the first term `exp(-nc / 2) chdtr(df, x)` for a subnormal `x`, as `x / 2`
663 // rounds, to `~(1 + nc) x` relative
664 if x < 2.0 * f64::MIN_POSITIVE {
665 return crate::chdtr(df, x) * (-xnonc).exp();
666 }
667 let icent = xnonc.floor().max(1.0);
668 let centwt = poisson_weight(icent, xnonc);
669 let chid2 = x / 2.0;
670 let mut adn = df / 2.0 + icent;
671 // in units of `2^scale` where `P(adn, chid2)` underflows, as the terms below `icent` need not
672 let (mut pdn, mut scale) = igam_scaled(adn, chid2);
673 let scale_up = scale;
674 let mut pup = pdn;
675 let mut ssum = centwt * pdn;
676
677 let mut wt = centwt;
678 let mut i = icent;
679
680 // chid2^adn exp(-chid2) / Gamma(adn + 1)
681 let mut dnterm = (ln_gamma_term(adn, chid2) - f64::from(scale) * LN_2).exp();
682
683 // as in `cumfnc`, and in cdflib
684 loop {
685 wt *= i / xnonc;
686 i -= 1.0;
687 // `dnterm` is scaled via the denominator, as scaling it first can make it subnormal
688 let shift = rescale(pdn, adn, chid2, &mut scale, &mut [&mut pdn, &mut ssum]);
689 dnterm = dnterm * adn / ldexp_f64(chid2, shift);
690 adn -= 1.0;
691 pdn += dnterm;
692 ssum += wt * pdn;
693 if !(wt * pdn > eps * ssum && i > 0.0 && wt >= f64::MIN_POSITIVE) {
694 break;
695 }
696 }
697
698 i = icent;
699 wt = centwt;
700
701 let mut aup = df / 2.0 + icent;
702 let mut upterm = (ln_gamma_term(aup, chid2) - f64::from(scale) * LN_2).exp();
703 pup = ldexp_f64(pup, scale_up - scale);
704
705 loop {
706 i += 1.0;
707 wt *= xnonc / i;
708 pup -= upterm;
709 aup += 1.0;
710 upterm *= chid2 / aup;
711 ssum += wt * pup;
712 if !(wt * pup > eps * ssum) {
713 break;
714 }
715 }
716
717 ldexp_f64(ssum, scale)
718}
719
720/// CDF of the noncentral F distribution
721///
722/// Corresponds to [`scipy.special.ncfdtr`][ncfdtr].
723///
724/// [ncfdtr]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ncfdtr.html
725///
726/// # See also
727/// - [`ncfdtri`]: Inverse of [`ncfdtr`] with respect to `f`
728/// - [`fdtr`](crate::fdtr): CDF of the (central) F distribution
729#[must_use]
730pub fn ncfdtr(dfn: f64, dfd: f64, nc: f64, f: f64) -> f64 {
731 // as in SciPy, also for infinite parameters
732 if f == f64::INFINITY && dfn > 0.0 && dfd > 0.0 && nc >= 0.0 {
733 return 1.0;
734 }
735 if !(is_pos_finite(dfn) && is_pos_finite(dfd) && (0.0..=NC_MAX).contains(&nc) && f >= 0.0) {
736 return f64::NAN;
737 }
738 // Unlike in SciPy, cdflib's series (A&S 26.6.20), as Boost's is inaccurate where its central
739 // term underflows, e.g. `ncfdtr(5, 50, 1500, 5) = 1.7e-188`, not `8.2e-161`.
740 let p = cumfnc(f, dfn, dfd, nc);
741 // the rounding of the sum can exceed 1, but keep NaN
742 if p > 1.0 { 1.0 } else { p }
743}
744
745/// Inverse of [`ncfdtr`] with respect to `f`
746///
747/// Corresponds to [`scipy.special.ncfdtri`][ncfdtri].
748///
749/// [ncfdtri]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ncfdtri.html
750///
751/// # See also
752/// - [`ncfdtridfd`]: Inverse of [`ncfdtr`] with respect to `dfd`
753/// - [`ncfdtridfn`]: Inverse of [`ncfdtr`] with respect to `dfn`
754/// - [`ncfdtrinc`]: Inverse of [`ncfdtr`] with respect to `nc`
755#[must_use]
756pub fn ncfdtri(dfn: f64, dfd: f64, nc: f64, p: f64) -> f64 {
757 if !(is_pos_finite(dfn)
758 && is_pos_finite(dfd)
759 && (0.0..=NC_MAX).contains(&nc)
760 && (0.0..=1.0).contains(&p))
761 {
762 return f64::NAN;
763 }
764 limit_if_p_is_0_or_1(p, true).unwrap_or_else(|| {
765 // as low as the smallest subnormal, like `chndtri`
766 find_positive_root(
767 |f| cumfnc(f, dfn, dfd, nc) - p,
768 f64::from_bits(1),
769 f64::MAX,
770 true,
771 )
772 })
773}
774
775/// CDF of the noncentral F distribution, from cdflib's `cumfnc`.
776///
777/// It sums the series A&S 26.6.20 forward and backward from the term with the largest Poisson
778/// weight, with the incomplete beta functions from the recurrences A&S 26.5.16.
779///
780/// Unlike in SciPy,
781/// - the series is summed to machine precision, instead of to a relative tolerance of `1e-4` or
782/// until the sum is below `1e-300`,
783/// - `nc` is treated as 0 below `2 MIN_POSITIVE` instead of `1e-10`,
784/// - the central Poisson weight is computed with `igam_fac`, since `exp` loses `~nc ln(nc) eps`,
785/// - the first terms of the recurrences are computed with `lbeta`, also if `a < 2`, where the
786/// `lgam` differences lose `~b ln(b) eps`,
787/// - `ln(1 - x)` is computed with `ln_1p`,
788/// - subnormal `x` is handled separately, since it rounds,
789/// - the beta terms are rescaled by powers of 2 if the central one underflows,
790/// - `cumf` and `bratio` are replaced by [`fdtr`](crate::fdtr) and `betainc_xy`.
791fn cumfnc(f: f64, dfn: f64, dfd: f64, pnonc: f64) -> f64 {
792 let eps = f64::EPSILON;
793
794 if !(f > 0.0) {
795 return 0.0;
796 }
797 // the weights below are subnormal if `nc / 2 < MIN_POSITIVE`, where `nc` changes the CDF by
798 // less than `nc / 2` relative
799 if !(pnonc >= 2.0 * f64::MIN_POSITIVE) {
800 return fdtr(dfn, dfd, f);
801 }
802 if !(pnonc <= NC_MAX) {
803 return f64::NAN;
804 }
805
806 let xnonc = pnonc / 2.0;
807 // Unlike in cdflib, the first term `exp(-nc / 2) I_x(dfn / 2, dfd / 2)` separately if
808 // `dfn / 2 + dfd / 2 < 1 / 2`, as it can exceed the next by `~1 / (dfn / 2 + dfd / 2)`
809 // relative, past where the loop below stops, which then starts above it
810 let i_min = if dfn + dfd < 1.0 { 1.0 } else { 0.0 };
811 let icent = xnonc.floor().max(i_min + 1.0);
812 let centwt = poisson_weight(icent, xnonc);
813 let prod = dfn * f;
814 let dsum = dfd + prod;
815 // Unlike in cdflib, a subnormal `x = dfn f / dsum`, which rounds: if `dfn f < eps`, the first
816 // term `exp(-nc / 2) fdtr(dfn, dfd, f)`, to `~(1 + nc) dfn f` relative, else (`dfd > 1e291`)
817 // the noncentral chi-square CDF of `dfn f`
818 if prod / dsum < 2.0 * f64::MIN_POSITIVE {
819 if prod >= eps {
820 return cumchn(prod, dfn, pnonc);
821 }
822 return fdtr(dfn, dfd, f) * (-xnonc).exp();
823 }
824 // `dfd / dsum`, also if `prod` overflows
825 let mut yy = if prod.is_finite() {
826 dfd / dsum
827 } else {
828 dfd / dfn / f
829 };
830 let xx;
831 // `ln` of the rounded complement would lose ~eps / min(xx, yy), which `b` or `adn` amplify
832 let (lnxx, lnyy);
833 if yy > 0.5 {
834 // Unlike in cdflib, without the rounding of a subnormal `prod`
835 xx = fdtr_w(dfn, dfd, f).0;
836 yy = 1.0 - xx;
837 (lnxx, lnyy) = (xx.ln(), (-xx).ln_1p());
838 } else {
839 xx = 1.0 - yy;
840 // without the rounding of a subnormal `yy`
841 let ln_y = if !prod.is_finite() {
842 dfd.ln() - dfn.ln() - f.ln()
843 } else if yy < f64::MIN_POSITIVE {
844 dfd.ln() - dsum.ln()
845 } else {
846 yy.ln()
847 };
848 (lnxx, lnyy) = ((-yy).ln_1p(), ln_y);
849 }
850 let mut adn = dfn / 2.0 + icent;
851 let mut aup = adn;
852 // Unlike in cdflib, if `dfd / 2` is subnormal, where it rounds (e.g. to 0), the series for
853 // `b = MIN_POSITIVE` scaled by `dfd / (2 b)`, as its terms are `O(b)` (but the first if
854 // `dfn / 2 ~ b`, which is separate then)
855 let b = (dfd / 2.0).max(f64::MIN_POSITIVE);
856 // If `I_x(adn, b)` underflows, the beta terms are carried as multiples of `2^scale`, since the
857 // terms below `icent` can still be significant, e.g. if x is tiny.
858 // Unlike in cdflib, if `yy` is subnormal or 0, as it rounds: `1 - I_y(b, adn)`, with (DLMF
859 // 8.17.7) `I_y(b, adn) = y^b / (b B(adn, b)) F(b, 1 - adn; b + 1; y)`. If `adn > 1 / eps`, its
860 // limit `Q(b, z)` as `adn -> inf`, with `z = adn y`, up to `O(1 / adn)`, which avoids
861 // cancelling `ln(y)` and `ln(adn)`. Else, or if `z` is subnormal, `z < eps` and the first term
862 // suffices: the next is `b (1 - adn) y / (b + 1)` relative, so `< z / 35` relative to `1 - I`.
863 // `z` avoids the rounding of `yy`, and the overflow of `adn / dsum` for a tiny `dsum` (where
864 // `adn dfd = z dsum` is normal if `z >= eps`).
865 let z = if prod.is_finite() {
866 let r = adn / dsum;
867 if r.is_finite() {
868 r * dfd
869 } else {
870 adn * dfd / dsum
871 }
872 } else {
873 adn / dfn / f * dfd
874 };
875 let (mut betdn, mut scale) = if yy >= f64::MIN_POSITIVE {
876 betainc_scaled(adn, b, xx, yy, lnxx, lnyy)
877 } else if adn * eps > 1.0 && z >= f64::MIN_POSITIVE {
878 (igamc(b, z), 0)
879 } else {
880 (-(b * lnyy - ln_a_beta(b, adn)).exp_m1(), 0)
881 };
882 let scale_up = scale;
883 let mut betup = betdn;
884 let mut ssum = centwt * betdn;
885
886 let mut xmult = centwt;
887 let mut i = icent;
888
889 // x^adn y^b / (adn B(adn, b))
890 let (ln_cent, asymp) = ln_beta_term(adn, b, xx, yy, lnxx, lnyy);
891 let cent_term = (ln_cent - f64::from(scale) * LN_2).exp();
892 let mut dnterm = cent_term;
893
894 // Unlike in cdflib, at least once, as the central term underflows for a tiny `nc` while the
895 // next need not, with `>` instead of `>=`, which never ends if `eps * ssum` underflows, and not
896 // past the underflow of the Poisson weight, which gets stuck at a subnormal while the scaled
897 // `betdn` grows
898 loop {
899 xmult *= i / xnonc;
900 i -= 1.0;
901 // Unlike in cdflib, `dfn / 2` last, not `adn - 1`, which loses up to `~icent eps` of it
902 // (all if `dfn < eps`), while `I_x(dfn / 2, b)` depends on it relatively
903 adn = if i > 0.0 { adn - 1.0 } else { dfn / 2.0 };
904 let num = adn + 1.0;
905 let shift = rescale(
906 betdn,
907 num,
908 (adn + b) * xx,
909 &mut scale,
910 &mut [&mut betdn, &mut ssum],
911 );
912 // Unlike in cdflib, `xx` scaled first, as `(adn + b) xx` can round to a subnormal
913 dnterm = dnterm * num / ((adn + b) * ldexp_f64(xx, shift));
914 betdn += dnterm;
915 ssum += xmult * betdn;
916 if !(xmult * betdn > eps * ssum && i > i_min && xmult >= f64::MIN_POSITIVE) {
917 break;
918 }
919 }
920
921 i = icent + 1.0;
922 xmult = centwt;
923
924 // x^(aup - 1) y^b / ((aup - 1) B(aup - 1, b)), with `aup - 1` not rounded to 0 if dfn < eps
925 let a = dfn / 2.0 + (icent - 1.0);
926 // Unlike in cdflib, from the first term of the down sum if that avoids the cancellation: the
927 // result depends on the difference of both sums, so their first terms should share their
928 // rounding error, which is independent for `a` and `adn` otherwise
929 let mut upterm = if asymp {
930 ldexp_f64(cent_term, scale_up - scale) * aup / ((a + b) * xx)
931 } else {
932 (ln_beta_term(a, b, xx, yy, lnxx, lnyy).0 - f64::from(scale) * LN_2).exp()
933 };
934 betup = ldexp_f64(betup, scale_up - scale);
935
936 loop {
937 xmult *= xnonc / i;
938 i += 1.0;
939 aup += 1.0;
940 upterm *= (aup + b - 2.0) * xx / (aup - 1.0);
941 betup -= upterm;
942 ssum += xmult * betup;
943 if !(xmult * betup > eps * ssum) {
944 break;
945 }
946 }
947
948 let first = if i_min > 0.0 {
949 fdtr(dfn, dfd, f) * (-xnonc).exp()
950 } else {
951 0.0
952 };
953 ldexp_f64(ssum * (dfd / (2.0 * b)), scale) + first
954}
955
956/// Inverse of the noncentral F CDF with respect to `dfd`
957///
958/// Corresponds to [`scipy.special.ncfdtridfd`][ncfdtridfd].
959///
960/// [ncfdtridfd]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ncfdtridfd.html
961///
962/// # See also
963/// - [`ncfdtridfn`]: Inverse of the noncentral F CDF with respect to `dfn`
964/// - [`ncfdtrinc`]: Inverse of the noncentral F CDF with respect to `nc`
965/// - [`fdtridfd`]: Inverse of [`fdtr`](crate::fdtr) with respect to `b`
966#[must_use]
967pub fn ncfdtridfd(dfn: f64, p: f64, nc: f64, f: f64) -> f64 {
968 if !(dfn > 0.0 && (0.0..=1.0).contains(&p) && (0.0..=NC_MAX).contains(&nc) && is_pos_finite(f))
969 {
970 return f64::NAN;
971 }
972 limit_if_p_is_0_or_1(p, true)
973 .unwrap_or_else(|| find_df_root(|dfd| cumfnc(f, dfn, dfd, nc) - p, true))
974}
975
976/// Inverse of the noncentral F CDF with respect to `dfn`
977///
978/// Corresponds to [`scipy.special.ncfdtridfn`][ncfdtridfn].
979///
980/// [ncfdtridfn]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ncfdtridfn.html
981///
982/// # See also
983/// - [`ncfdtridfd`]: Inverse of the noncentral F CDF with respect to `dfd`
984/// - [`ncfdtrinc`]: Inverse of the noncentral F CDF with respect to `nc`
985#[must_use]
986pub fn ncfdtridfn(p: f64, dfd: f64, nc: f64, f: f64) -> f64 {
987 if !(dfd > 0.0 && (0.0..=1.0).contains(&p) && (0.0..=NC_MAX).contains(&nc) && is_pos_finite(f))
988 {
989 return f64::NAN;
990 }
991 // ncfdtr goes from exp(-nc/2) at dfn = 0 to chdtrc(dfd, dfd / f) at dfn = inf
992 let increasing = crate::chdtrc(dfd, dfd / f) > (-nc / 2.0).exp();
993 limit_if_p_is_0_or_1(p, increasing)
994 .unwrap_or_else(|| find_df_root(|dfn| cumfnc(f, dfn, dfd, nc) - p, increasing))
995}
996
997/// Inverse of the noncentral F CDF with respect to `nc`
998///
999/// Corresponds to [`scipy.special.ncfdtrinc`][ncfdtrinc].
1000///
1001/// [ncfdtrinc]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ncfdtrinc.html
1002///
1003/// # See also
1004/// - [`ncfdtridfd`]: Inverse of the noncentral F CDF with respect to `dfd`
1005/// - [`ncfdtridfn`]: Inverse of the noncentral F CDF with respect to `dfn`
1006#[must_use]
1007pub fn ncfdtrinc(dfn: f64, dfd: f64, p: f64, f: f64) -> f64 {
1008 if !(dfn > 0.0 && dfd > 0.0 && (0.0..=1.0).contains(&p) && is_pos_finite(f)) {
1009 return f64::NAN;
1010 }
1011 // the CDF decreases in nc
1012 limit_if_p_is_0_or_1(p, false).unwrap_or_else(|| {
1013 find_positive_root(
1014 |nc| cumfnc(f, dfn, dfd, nc) - p,
1015 f64::MIN_POSITIVE,
1016 NC_MAX,
1017 false,
1018 )
1019 })
1020}
1021
1022/// CDF of the noncentral t distribution
1023///
1024/// Corresponds to [`scipy.special.nctdtr`][nctdtr]. It is slower, but also accurate where SciPy's
1025/// loses all digits or returns NaN, e.g. for `t < 0 < nc` or a large `nc`.
1026///
1027/// [nctdtr]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.nctdtr.html
1028///
1029/// # See also
1030/// - [`stdtr`](crate::stdtr): CDF of the (central) Student's t distribution
1031/// - [`nctdtridf`]: Inverse of [`nctdtr`] with respect to `df`
1032/// - [`nctdtrinc`]: Inverse of [`nctdtr`] with respect to `nc`
1033#[must_use]
1034pub fn nctdtr(df: f64, nc: f64, t: f64) -> f64 {
1035 if !(df > 0.0 && !nc.is_nan() && !t.is_nan()) {
1036 f64::NAN
1037 } else if t.is_infinite() {
1038 // the limits of SciPy, where infinite `t` goes before infinite `nc`
1039 if t > 0.0 { 1.0 } else { 0.0 }
1040 } else if nc.is_infinite() {
1041 f64::NAN
1042 } else if df.is_infinite() {
1043 crate::ndtr(t - nc)
1044 } else if t == 0.0 || 0.5 * df == 0.0 {
1045 // the `df -> 0` limit, also if `df / 2` underflows
1046 crate::ndtr(-nc)
1047 } else {
1048 // Unlike in SciPy, quadrature, as Boost's series cancels for `t < 0 < nc`, e.g.
1049 // `nctdtr(10, 10, -1) = 2.6e-27`
1050 nct_quad(t, df, nc)
1051 }
1052}
1053
1054/// Inverse of the noncentral t CDF with respect to `t`
1055///
1056/// Corresponds to [`scipy.special.nctdtrit`][nctdtrit]. It is slower, but also accurate where
1057/// SciPy's loses all digits or returns NaN, e.g. for a small `df` or a large `nc`.
1058///
1059/// [nctdtrit]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.nctdtrit.html
1060///
1061/// # See also
1062/// - [`nctdtr`]: CDF of the noncentral t distribution
1063/// - [`stdtri`](crate::stdtri): Inverse of the (central) Student's t CDF
1064#[must_use]
1065pub fn nctdtrit(df: f64, nc: f64, p: f64) -> f64 {
1066 if !(df > 0.0 && nc.is_finite() && (0.0..=1.0).contains(&p)) {
1067 f64::NAN
1068 } else if df.is_infinite() || p == 0.0 || p == 1.0 {
1069 // Unlike in SciPy, -inf if `p = 0`, instead of inf
1070 nc + crate::ndtri(p)
1071 } else if p > 0.5 {
1072 // `F(t; nc) = 1 - F(-t; -nc)`, since `1 - p` is exact, but not `nctdtr` near 1
1073 -nctdtrit(df, -nc, 1.0 - p)
1074 } else {
1075 // Unlike in SciPy, bracketed, with Chandrupatla in `asinh(t)`, as the tails can be as
1076 // heavy as `|t|^-df`
1077 let func = |x: f64| nctdtr(df, nc, x.sinh()) - p;
1078 let x_max = f64::MAX.asinh();
1079 let x0 = (nc + crate::ndtri(p)).asinh();
1080 let (xl, xr, f_xl, f_xr, bracket_status) =
1081 bracket_root_for_cdf_inversion(func, x0, -x_max, x_max, -1.0, 1.0, 2.0, 2.0, true, 64);
1082 // relative and absolute, as the rounding of `nctdtr` can jump at `t = 0`
1083 let tol = f64::EPSILON;
1084 match bracket_status {
1085 0 => match find_root_chandrupatla(func, xl, xr, f_xl, f_xr, tol, tol, 100) {
1086 (x, 0) => x.sinh(),
1087 _ => f64::NAN,
1088 },
1089 1 => f64::NEG_INFINITY,
1090 2 => f64::INFINITY,
1091 _ => f64::NAN,
1092 }
1093 }
1094}
1095
1096/// CDF of the noncentral t distribution, from cdflib's `cumtnc`.
1097///
1098/// It sums the series for the upper tail on p. 532 of Johnson, Kotz and Balakrishnan, Continuous
1099/// Univariate Distributions, Vol. 2, 2nd ed. (1995), forward and backward from the term with the
1100/// largest Poisson weight.
1101///
1102/// Unlike in SciPy, and as in [`cumfnc`],
1103/// - the series is summed to machine precision, instead of to a relative tolerance of `1e-7`,
1104/// - `t` and `nc` are treated as 0 below `eps` and `1e-102` instead of `1e-10`, and the shortcuts
1105/// for `B(2 cent)` and `B(2 cent + 1)` near 0 or 1 are dropped, since they cut off the sum at
1106/// `1e-10`, or lose the terms below `cent`,
1107/// - the Poisson weights are computed with `igam_fac` (directly if `cent = 1`), and `ln(1 - x)`
1108/// with `ln_1p`,
1109/// - `s(cent)` is computed with `lbeta`, since `lgam` loses `~df ln(df) eps`,
1110/// - the beta terms are rescaled by powers of 2 if the central ones underflow,
1111/// - `cumt`, `cumnor` and `bratio` are replaced by [`stdtr`](crate::stdtr),
1112/// [`ndtr`](crate::ndtr) and `betainc_xy`.
1113///
1114/// As in SciPy, the lower tail for `t > 0` is computed as 1 minus the upper tail, so that it is
1115/// lost below `~eps`, and the series cancels if `nc` and `t` have opposite signs.
1116fn cumtnc(t: f64, df: f64, pnonc: f64) -> f64 {
1117 let tiny = f64::EPSILON;
1118
1119 // the weights below, `~lambda^1.5` if `lambda = nc^2 / 2 < 1`, are subnormal if `|nc| < 1e-102`
1120 if pnonc.abs() < 1e-102 {
1121 return crate::stdtr(df, t);
1122 }
1123 let qrevs = t < 0.0;
1124 let tt = t.abs();
1125 let dpnonc = if qrevs { -pnonc } else { pnonc };
1126 let pnonc2 = dpnonc * dpnonc;
1127 let t2 = tt * tt;
1128 // t is effectively 0, also if 1 - x underflows
1129 if tt <= tiny || t2 / df == 0.0 {
1130 return crate::ndtr(-pnonc);
1131 }
1132
1133 let lmbda = 0.5 * pnonc2;
1134 let x = df / (df + t2);
1135 // not t2 / (df + t2), which is NaN if t2 overflows
1136 let omx = 1.0 / (1.0 + df / t2);
1137 let (lnx, lnomx) = if x > 0.5 {
1138 ((-omx).ln_1p(), omx.ln())
1139 } else {
1140 (x.ln(), (-x).ln_1p())
1141 };
1142 // Case : i = lambda
1143 let cent = lmbda.floor().max(1.0);
1144 // Compute d=T(2i) and e=t(2i+1), offset by exp(-lambda)
1145 // lambda^cent exp(-lambda) / cent! and lambda^(cent + 1/2) exp(-lambda) / Gamma(cent + 3/2),
1146 // where `igam_fac` loses `~|ln(lambda)| eps` if lambda < 1
1147 let (dcent, mut ecent) = if cent == 1.0 {
1148 let dcent = lmbda * (-lmbda).exp();
1149 (dcent, dcent * lmbda.sqrt() / (0.75 * SQRT_PI))
1150 } else {
1151 (
1152 igam_fac(cent + 1.0, lmbda) / lmbda,
1153 igam_fac(cent + 1.5, lmbda) / lmbda,
1154 )
1155 };
1156 if dpnonc < 0.0 {
1157 ecent = -ecent;
1158 }
1159 // Compute bcent=B(2*cent) and bbcent=B(2*cent+1). If they underflow, the terms are carried as
1160 // multiples of `2^scale`, since the later ones can still be significant.
1161 let (bcent, scale_b) = betainc_scaled(0.5 * df, cent + 0.5, x, omx, lnx, lnomx);
1162 let (bbcent, scale_bb) = betainc_scaled(0.5 * df, cent + 1.0, x, omx, lnx, lnomx);
1163 let scale_cent = scale_b.max(scale_bb);
1164 let bcent = ldexp_f64(bcent, scale_b - scale_cent);
1165 let bbcent = ldexp_f64(bbcent, scale_bb - scale_cent);
1166 let mut scale = scale_cent;
1167
1168 // First term in ccum is D*B + E*BB
1169 let mut ccum = dcent * bcent + ecent * bbcent;
1170 // Compute s(cent) = B(2*(cent+1)) - B(2*cent))
1171 let scent =
1172 (-lbeta(0.5 * df, cent + 0.5) - (cent + 0.5).ln() + 0.5 * df * lnx + (cent + 0.5) * lnomx
1173 - f64::from(scale) * LN_2)
1174 .exp();
1175 // Compute ss(cent) = B(2*cent+3) - B(2*cent+1)
1176 let sscent =
1177 (-lbeta(0.5 * df, cent + 1.0) - (cent + 1.0).ln() + 0.5 * df * lnx + (cent + 1.0) * lnomx
1178 - f64::from(scale) * LN_2)
1179 .exp();
1180 // Sum forward. If nc < 0, the sum can cancel to 0 or below, and terms that are NaN end it too.
1181 let mut xi = cent + 1.0;
1182 let mut twoi = 2.0 * xi;
1183 let mut d = dcent;
1184 let mut e = ecent;
1185 let mut b = bcent;
1186 let mut s = scent;
1187 let mut bb = bbcent;
1188 let mut ss = sscent;
1189 loop {
1190 rescale(
1191 (b + s).max(bb + ss),
1192 1.0,
1193 1.0,
1194 &mut scale,
1195 &mut [&mut b, &mut bb, &mut s, &mut ss, &mut ccum],
1196 );
1197 b += s;
1198 bb += ss;
1199 d *= lmbda / xi;
1200 e *= lmbda / (xi + 0.5);
1201 let term = d * b + e * bb;
1202 ccum += term;
1203 s *= omx * (df + twoi - 1.0) / (twoi + 1.0);
1204 ss *= omx * (df + twoi) / (twoi + 2.0);
1205 xi += 1.0;
1206 twoi = 2.0 * xi;
1207 // if scaled, not past the underflow of the Poisson weights, which would get stuck at a
1208 // subnormal, while `b` and `bb` grow
1209 if !(term.abs() > f64::EPSILON * ccum.abs())
1210 || scale < 0 && d < f64::MIN_POSITIVE && e.abs() < f64::MIN_POSITIVE
1211 {
1212 break;
1213 }
1214 }
1215 // Sum Backward
1216 xi = cent;
1217 twoi = 2.0 * xi;
1218 d = dcent;
1219 e = ecent;
1220 let shift = scale_cent - scale;
1221 b = ldexp_f64(bcent, shift);
1222 bb = ldexp_f64(bbcent, shift);
1223 s = ldexp_f64(scent, shift) * (1.0 + twoi) / ((df + twoi - 1.0) * omx);
1224 ss = ldexp_f64(sscent, shift) * (2.0 + twoi) / ((df + twoi) * omx);
1225 loop {
1226 b -= s;
1227 bb -= ss;
1228 d *= xi / lmbda;
1229 e *= (xi + 0.5) / lmbda;
1230 let term = d * b + e * bb;
1231 ccum += term;
1232 xi -= 1.0;
1233 if xi < 0.5 {
1234 break;
1235 }
1236 twoi = 2.0 * xi;
1237 s *= (1.0 + twoi) / ((df + twoi - 1.0) * omx);
1238 ss *= (2.0 + twoi) / ((df + twoi) * omx);
1239 if !(term.abs() > f64::EPSILON * ccum.abs()) {
1240 break;
1241 }
1242 }
1243 // Due to roundoff error the answer may not lie between zero and one
1244 // Force it to do so
1245 let ccum = ldexp_f64(0.5 * ccum, scale).clamp(0.0, 1.0);
1246 if qrevs { ccum } else { 1.0 - ccum }
1247}
1248
1249/// CDF of the noncentral t distribution, as `E[ndtr(t W - nc)]` over the chi distribution of
1250/// `W = sqrt(V / df)` with `V ~ chi^2(df)`, by quadrature in `s = ln(W)`.
1251///
1252/// The integrand is unimodal in `s`. Below `w0` it is split into `ndtr(-nc) P(W < w0)` and the
1253/// difference, whose tail is far shorter if `df` is small.
1254fn nct_quad(t: f64, df: f64, nc: f64) -> f64 {
1255 // above the `50 eps` floor of the error estimate of `quad`
1256 const EPSREL: f64 = 1e-13;
1257 let a = 0.5 * df;
1258 // the density `2 x^a e^-x / Gamma(a)` of `s`, with `x = a e^(2 s)` left unrounded
1259 let peak = 2.0 * igam_fac(a, a);
1260 let density = |s: f64| {
1261 let u = 2.0 * s;
1262 // `ln(x / a) - (x / a - 1)`
1263 let ln_ratio = if u.abs() < 1.0 {
1264 log1pmx(u.exp_m1())
1265 } else {
1266 u - u.exp_m1()
1267 };
1268 peak * (a * ln_ratio).exp()
1269 };
1270
1271 let phi0 = crate::ndtr(-nc);
1272 let w0 = (0.5 / (t.abs() * (nc.abs() + 2.0))).min(0.5);
1273 let s0 = w0.ln();
1274 // `P(W < w0)`, by its leading term `y^a / Gamma(a + 1)` where `y = a w0^2` underflows
1275 let y = a * w0 * w0;
1276 let head = phi0
1277 * if y < f64::MIN_POSITIVE {
1278 (a * (a.ln() + 2.0 * s0)).exp() * crate::rgamma(a + 1.0)
1279 } else {
1280 igam(a, y)
1281 };
1282 // `t e^s - nc`, from a finite `t - nc` if `e^s > 1/2`, as `e^s` rounds away a small `s`, with
1283 // the rounding error of `t - nc`, which would otherwise bias all nodes alike
1284 let (t_nc, t_nc_err) = two_sum(t, -nc);
1285 let z = |s: f64| {
1286 if s > -LN_2 && t_nc.is_finite() {
1287 t_nc + (t * s.exp_m1() + t_nc_err)
1288 } else {
1289 t * s.exp() - nc
1290 }
1291 };
1292 // the difference has the sign of `t`, and its tail decays as `w^(df + 1)`
1293 let diff = |s: f64| density(s) * (crate::ndtr(z(s)) - phi0).abs();
1294 let below = quad_unimodal(diff, f64::NEG_INFINITY, s0, s0, 1.0 / (df + 1.0), EPSREL);
1295
1296 // the derivatives of `ln(density(s) ndtr(z))`, with `z = t w - nc` and `w = e^s`
1297 let slopes = |s: f64| {
1298 let w = s.exp();
1299 let (x, z) = (t * w, z(s));
1300 // ndtr'(z) / ndtr(z)
1301 let h = SQRT_FRAC_2_PI / erfcx(-z / SQRT_2);
1302 let xh = x * h;
1303 let d1 = xh - df * (2.0 * s).exp_m1();
1304 // clamped, as `x z` can overflow where `x h` is 0
1305 let d2 = -2.0 * df * w * w + xh * (1.0 - x * (z + h)).max(-f64::MAX);
1306 (d1, d2)
1307 };
1308 let d1 = |s: f64| slopes(s).0;
1309 // the mode, to well within the width `~1 / sqrt(2 df)` of the density
1310 let mode = if d1(s0) > 0.0 {
1311 // bracketed in doubling steps from 0, since the mode is `~x h / (2 df)` if `df` is large
1312 let width = 1.0 / (df + 1.0).sqrt();
1313 let up = d1(0.0) > 0.0;
1314 let (mut near, mut step) = (0.0, width);
1315 let far = loop {
1316 let far = if up { near + step } else { s0.max(near - step) };
1317 if (d1(far) > 0.0) != up {
1318 break far;
1319 }
1320 (near, step) = (far, 2.0 * step);
1321 };
1322 let (lo, hi) = if up { (near, far) } else { (far, near) };
1323 find_root_chandrupatla(d1, lo, hi, d1(lo), d1(hi), 1e-8, 1e-3 * width, 100).0
1324 } else {
1325 s0
1326 };
1327 // at most 1, the scale of the density if `df` is small, and at most `1 / |x|`, the scale of the
1328 // step of `ndtr(x - nc)` that the curvature misses beyond it
1329 let x = t * mode.exp();
1330 let width = 1.0 / (-slopes(mode).1).max(1.0).max(x * x).min(f64::MAX).sqrt();
1331 let integrand = |s: f64| density(s) * crate::ndtr(z(s));
1332 let above = quad_unimodal(integrand, s0, f64::INFINITY, mode, width, EPSREL);
1333
1334 // the rounding of the sum can exceed 1, but keep NaN
1335 let p = head + t.signum() * below + above;
1336 if p > 1.0 { 1.0 } else { p }
1337}
1338
1339/// The largest `|nc|` for which [`cumtnc`] is computed, as in cdflib, since it sums `~12 |nc|`
1340/// terms.
1341const NCT_MAX: f64 = 1e6;
1342
1343/// Inverse of the noncentral t CDF with respect to `df`
1344///
1345/// Corresponds to [`scipy.special.nctdtridf`][nctdtridf].
1346///
1347/// [nctdtridf]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.nctdtridf.html
1348///
1349/// # See also
1350/// - [`nctdtrinc`]: Inverse of the noncentral t CDF with respect to `nc`
1351/// - [`stdtridf`]: Inverse of [`stdtr`](crate::stdtr) with respect to `nu`
1352#[must_use]
1353pub fn nctdtridf(p: f64, nc: f64, t: f64) -> f64 {
1354 // the CDF is ndtr(-nc) if t = 0, and 1 or 0 if t = +-inf, independent of df
1355 if !((0.0..=1.0).contains(&p) && nc.abs() <= NCT_MAX && t != 0.0 && t.is_finite()) {
1356 return f64::NAN;
1357 }
1358 let increasing = t > 0.0;
1359 if let Some(df) = limit_if_p_is_0_or_1(p, increasing) {
1360 return df;
1361 }
1362 let func = |df: f64| cumtnc(t, df, nc) - p;
1363 // The CDF goes from ndtr(-nc) at df = 0 to ndtr(t - nc) at df = inf. If p lies outside, and
1364 // also beyond the CDF at the search points, only an extremum in between can reach it, which
1365 // saves the searches of `find_df_root` up to its bounds, of ~110 CDFs of ~12 |nc| terms each.
1366 let (at_0, at_inf) = (crate::ndtr(-nc) - p, crate::ndtr(t - nc) - p);
1367 if (at_0 > 0.0 && at_inf > 0.0) || (at_0 < 0.0 && at_inf < 0.0) {
1368 let closest = if at_0.abs() < at_inf.abs() {
1369 0.0
1370 } else {
1371 f64::INFINITY
1372 };
1373 // With `W = sqrt(V / df)` and `V ~ chi^2(df)`, the CDF is `E[ndtr(t W - nc)]`, so that its
1374 // distance from 0 if `t > 0`, or from 1 if `t < 0`, is `E[ndtr(|t| W - s)]` with
1375 // `s = sign(t) nc`. This is at least `ndtr(-s)`, and by Markov's inequality
1376 // `P(W >= w) <= 1 / w^2` with `w = s / (2 |t|)`, at most `4 t^2 / s^2 + ndtr(-s / 2)` if
1377 // `s > 0`, and the same distance `q` of `p` must lie in between.
1378 let (q, s) = if t > 0.0 { (p, nc) } else { (1.0 - p, -nc) };
1379 // `q < ndtr(-s)`, without the rounding of `1 - p`
1380 let below_min = (t > 0.0) == (at_0 > 0.0);
1381 if below_min || s > 0.0 && q > 4.0 * t * t / (s * s) + crate::ndtr(-s / 2.0) {
1382 return closest;
1383 }
1384 if let Some(points) = scan_same_sign(func) {
1385 return find_extremum_root(func, &points, increasing).unwrap_or(closest);
1386 }
1387 }
1388 find_df_root(func, increasing)
1389}
1390
1391/// Inverse of the noncentral t CDF with respect to `nc`
1392///
1393/// Corresponds to [`scipy.special.nctdtrinc`][nctdtrinc].
1394///
1395/// [nctdtrinc]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.nctdtrinc.html
1396///
1397/// # See also
1398/// - [`nctdtridf`]: Inverse of the noncentral t CDF with respect to `df`
1399/// - [`stdtridf`]: Inverse of [`stdtr`](crate::stdtr) with respect to `nu`
1400#[must_use]
1401pub fn nctdtrinc(df: f64, p: f64, t: f64) -> f64 {
1402 if !(df > 0.0 && (0.0..=1.0).contains(&p) && t.is_finite()) {
1403 return f64::NAN;
1404 }
1405 // The CDF decreases in nc, from 1 at -inf to 0 at inf.
1406 if p == 0.0 || p == 1.0 {
1407 return if p == 0.0 {
1408 f64::INFINITY
1409 } else {
1410 f64::NEG_INFINITY
1411 };
1412 }
1413 let func = |nc: f64| cumtnc(t, df, nc) - p;
1414 // The bracket is expanded in steps of 1, 2, 4, ... from 0, and 64 steps are more than enough
1415 // to reach NCT_MAX.
1416 let (xl, xr, f_xl, f_xr, bracket_status) = bracket_root_for_cdf_inversion(
1417 func, 0.0, -NCT_MAX, NCT_MAX, -1.0, 1.0, 2.0, 2.0, false, 64,
1418 );
1419 match bracket_status {
1420 0 => match find_root_chandrupatla(func, xl, xr, f_xl, f_xr, f64::EPSILON, 1e-100, 100) {
1421 (nc, 0) => nc,
1422 _ => f64::NAN,
1423 },
1424 1 => f64::NEG_INFINITY,
1425 2 => f64::INFINITY,
1426 _ => f64::NAN,
1427 }
1428}