@numero-uno-jpn/rstats 0.15.0 → 0.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.ja.md +8 -8
  3. package/README.md +8 -8
  4. package/dist/chunks/chunk-2CUKVVRO.js +2 -0
  5. package/dist/chunks/{chunk-4XGKAHD3.js → chunk-3WQCKGKP.js} +2 -2
  6. package/dist/chunks/{chunk-7XHAE2LG.js → chunk-4Z2XDWKV.js} +1 -1
  7. package/dist/chunks/{chunk-QQIWOGHR.js → chunk-AJBLCNZ7.js} +2 -2
  8. package/dist/chunks/chunk-D4F7GQAY.js +2 -0
  9. package/dist/chunks/chunk-EBQMGCQZ.js +2 -0
  10. package/dist/chunks/{chunk-WEWXYHPR.js → chunk-HBMHR5SS.js} +2 -2
  11. package/dist/chunks/{chunk-HS7KIFMR.js → chunk-IBPWRQIF.js} +2 -2
  12. package/dist/chunks/chunk-JLAH3X77.js +2 -0
  13. package/dist/chunks/chunk-LG74QY5U.js +2 -0
  14. package/dist/chunks/{chunk-A3XZUJCP.js → chunk-PEYGUK32.js} +2 -2
  15. package/dist/chunks/{chunk-HNLKOICT.js → chunk-PWVQVJTP.js} +1 -1
  16. package/dist/chunks/{chunk-AEFWSUZ2.js → chunk-Q4PGYESP.js} +2 -2
  17. package/dist/chunks/{chunk-GZTLODPK.js → chunk-RCAL4VHM.js} +2 -2
  18. package/dist/chunks/{chunk-XMTYTJT6.js → chunk-SREPSVTT.js} +2 -2
  19. package/dist/chunks/chunk-UFT662QZ.js +2 -0
  20. package/dist/chunks/{chunk-CJ5ETQCK.js → chunk-VWJ74UHC.js} +2 -2
  21. package/dist/chunks/{chunk-VAPGDPHM.js → chunk-XNPU54NH.js} +1 -1
  22. package/dist/chunks/{chunk-PRDF6IU6.js → chunk-XPLDEK6D.js} +2 -2
  23. package/dist/chunks/{chunk-LWUTCYTZ.js → chunk-YGT4P7EU.js} +1 -1
  24. package/dist/chunks/{chunk-7GEYDIQC.js → chunk-YVREYVI2.js} +2 -2
  25. package/dist/descriptive.js +2 -2
  26. package/dist/distributions/arcsine.js +48 -4
  27. package/dist/distributions/beta.d.ts +1 -1
  28. package/dist/distributions/beta.js +64 -1
  29. package/dist/distributions/exponential.js +11 -2
  30. package/dist/distributions/f.js +104 -21
  31. package/dist/distributions/gamma.d.ts +13 -2
  32. package/dist/distributions/gamma.js +91 -12
  33. package/dist/distributions/geometric.js +16 -3
  34. package/dist/distributions/invgamma.js +56 -10
  35. package/dist/distributions/kumaraswamy.js +98 -17
  36. package/dist/distributions/lognormal.js +28 -4
  37. package/dist/distributions/nbeta.js +540 -37
  38. package/dist/distributions/nchisq.d.ts +25 -0
  39. package/dist/distributions/nchisq.js +396 -60
  40. package/dist/distributions/negbinomial.js +20 -5
  41. package/dist/distributions/normal.js +3 -0
  42. package/dist/distributions/nt.js +263 -51
  43. package/dist/distributions/pareto.js +68 -19
  44. package/dist/distributions/signrank.js +73 -20
  45. package/dist/distributions/t.js +48 -10
  46. package/dist/distributions/triangular.js +66 -27
  47. package/dist/distributions/tukey.js +94 -50
  48. package/dist/distributions/uniform.js +12 -9
  49. package/dist/distributions/weibull.js +43 -8
  50. package/dist/distributions.js +2 -2
  51. package/dist/internal/ddexp.d.ts +5 -0
  52. package/dist/internal/ddexp.js +28 -3
  53. package/dist/internal/discrete.js +30 -7
  54. package/dist/internal/invert.js +49 -0
  55. package/dist/internal/noncentral.d.ts +34 -0
  56. package/dist/internal/noncentral.js +115 -2
  57. package/dist/internal/poissonMixture.d.ts +7 -2
  58. package/dist/internal/poissonMixture.js +113 -32
  59. package/dist/linalg.js +2 -2
  60. package/dist/mixed.js +2 -2
  61. package/dist/numerics.js +2 -2
  62. package/dist/rstats.js +14 -14
  63. package/dist/special/dd.d.ts +1 -1
  64. package/dist/special/dd.js +4 -1
  65. package/dist/special/igam.js +93 -15
  66. package/dist/special/incbet.d.ts +10 -0
  67. package/dist/special/incbet.js +154 -48
  68. package/dist/special/incbetLargeA.js +47 -13
  69. package/dist/special/incbetPrefactor.d.ts +52 -0
  70. package/dist/special/incbetPrefactor.js +92 -0
  71. package/dist/special/incbetTemme.js +15 -3
  72. package/dist/special/loader.js +33 -7
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +2 -2
  75. package/package.json +1 -1
  76. package/dist/chunks/chunk-4EOKNOXP.js +0 -2
  77. package/dist/chunks/chunk-CMPDE3SZ.js +0 -2
  78. package/dist/chunks/chunk-LU5FHU2O.js +0 -2
  79. package/dist/chunks/chunk-LVXAWWUX.js +0 -2
  80. package/dist/chunks/chunk-NYGWVZOC.js +0 -2
  81. package/dist/chunks/chunk-VSKWQMSG.js +0 -2
@@ -8,31 +8,47 @@
8
8
  // e_j = Gamma(a+b+j) / (Gamma(a+j+1) Gamma(b)) x^(a+j) (1-x)^b
9
9
  // = dbinom(a + j; a + b + j, x) b / (a + b + j)
10
10
  // The density of component j is e_j (a + j) / (x (1 - x)). The sums are done in src/internal/poissonMixture.ts.
11
+ // For a huge λ or extreme shapes the distribution is computed from X = Y / (Y + W) instead (see "Extreme parameters").
11
12
  //
12
13
  // The noncentral F is computed from the fact that X = m F / (n + m F) follows the noncentral beta (m/2, n/2, λ).
13
14
  // Its density is f_F(q) = Σ_j w_j e_j (a + j) / q (dx/dq and x (1 - x) cancel).
14
15
  // x and 1 - x are formed as a double-double pair (rounding is amplified by the parameters, as for the central distribution).
15
16
  import { dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
16
17
  import { invertContinuous } from "../internal/invert.js";
17
- import { mixtureCdf, mixtureDensity } from "../internal/poissonMixture.js";
18
+ import { kronrodAdaptive, narrowQuantile, quadratureControl, searchDoubles } from "../internal/noncentral.js";
19
+ import { gammaInc } from "../special/igam.js";
20
+ import { mixtureDensity, mixtureTail } from "../internal/poissonMixture.js";
18
21
  import { ddAdd, ddDiv, ddLog, ddMul, ddMulNum, ddNeg, twoProd, twoSum } from "../special/dd.js";
19
22
  import { lbeta, lbetaDD } from "../special/beta.js";
23
+ import { lgamma, lgamma1p } from "../special/gamma.js";
24
+ import { log1pmx } from "../special/log1pmx.js";
20
25
  import { digamma } from "../special/psigamma.js";
21
26
  import { betaIncDD } from "../special/incbet.js";
22
27
  import { dbinomExponent, dbinomRawDD } from "../special/loader.js";
23
28
  import { dbeta1, pbeta1, qbeta1 } from "./beta.js";
24
29
  import { dfDensity1, pf1, qf1 } from "./f.js";
25
- import { dnchisq1, negligibleTail, pnchisq1, qnchisq1 } from "./nchisq.js";
30
+ import { confirmQuantile, dnchisq1, dnchisqLogNear, gammaTailNear, negligibleTail, pnchisq1, qnchisq1 } from "./nchisq.js";
31
+ import { dgamma1 } from "./gamma.js";
26
32
  function betaKernel(a, b, xd, xcd) {
27
33
  const ab = twoSum(a, b);
28
- // For very small x the ratio underflows, so keep it scaled by 2^500
29
- const tiny = xd[0] < 1e-250;
30
- const xs = tiny ? [xd[0] * 2 ** 500, xd[1] * 2 ** 500] : xd;
34
+ // For very small x the ratio underflows, so keep it scaled by 2^(500 K) (also where a + b is tiny: the ratio at j = 1
35
+ // is x (a + b)/(a + 1), down to 1e-504), K units enough to bring x min(1, a + b) above 1e-250
36
+ const low = Math.log2(xd[0]) + Math.log2(Math.min(1, a + b));
37
+ const K = low < -830 ? Math.ceil((-830 - low) / 500) : 0;
38
+ let xs = xd;
39
+ for (let i = 0; i < K; i++)
40
+ xs = [xs[0] * 2 ** 500, xs[1] * 2 ** 500];
31
41
  return {
32
- ratioK: tiny ? -1 : 0,
42
+ ratioK: -K,
33
43
  cdf: (j, lower, log) => betaIncDD(a + j, b, xd, xcd, lower, log),
34
44
  inc: (j, log) => {
35
45
  const [s, corr] = incCorrection(a, b, j, xd);
46
+ if (!binomialHelpersApply(s, b, xd, xcd)) {
47
+ // Near subnormal x or for a tiny shape the binomial-probability helpers break down, as in incLogDD
48
+ const l = betaKernelIncLog(s, b, xd, xcd);
49
+ const lv = (typeof l === "number" ? l : l[0] + l[1]) + corr;
50
+ return log ? lv : Math.exp(lv);
51
+ }
36
52
  const c = b / (s + b);
37
53
  return log
38
54
  ? dbinomRawDD(s, b, xd, xcd, true) + Math.log(c) + corr
@@ -42,9 +58,10 @@ function betaKernel(a, b, xd, xcd) {
42
58
  ratio: (j) => ddDiv(ddMul(xs, ddAdd(ab, [j - 1, 0])), twoSum(a, j)),
43
59
  incLogDD: (j) => {
44
60
  // log e_j = log dbinom(a + j; a + b + j, x) + log(b / (a + b + j))
45
- // Near subnormal x the binomial-probability helpers break down, so build it from the log of the beta function
61
+ // Near subnormal x (n x underflows) or for a tiny shape (b = 1e-264: NaN) the binomial-probability helpers
62
+ // break down, so build it from the log of the beta function
46
63
  const [s, corr] = incCorrection(a, b, j, xd);
47
- if (!(xd[0] > 1e-305 && xcd[0] > 1e-305)) {
64
+ if (!binomialHelpersApply(s, b, xd, xcd)) {
48
65
  const l = betaKernelIncLog(s, b, xd, xcd);
49
66
  return typeof l === "number" ? l + corr : ddAdd(l, [corr, 0]);
50
67
  }
@@ -53,6 +70,10 @@ function betaKernel(a, b, xd, xcd) {
53
70
  },
54
71
  };
55
72
  }
73
+ /** Whether e_j can be taken from the binomial-probability helpers (dbinomRawDD, dbinomExponent) */
74
+ function binomialHelpersApply(s, b, xd, xcd) {
75
+ return xd[0] > 1e-305 && xcd[0] > 1e-305 && s > 1e-10 && b > 1e-10;
76
+ }
56
77
  /**
57
78
  * The shape a + j rounded to double, s, and the first-order change in log e_j from s to the exact a + j:
58
79
  * δ ∂log e/∂s with δ the rounding and ∂log e_j/∂s = log x + ψ(s + b) - ψ(s + 1) (e_j = x^s (1 - x)^b / (s B(s, b))).
@@ -67,12 +88,16 @@ function incCorrection(a, b, j, xd) {
67
88
  }
68
89
  /**
69
90
  * log e_j in double-double when x (or 1 - x) is near subnormal, for the shape s = a + j:
70
- * log e_j = -log B(s, b) - log(s) + s log x + b log(1 - x)
91
+ * log e_j = -log B(s, b) - log(s) + s log x + b log(1 - x).
92
+ * For s, b < 1, log(s B(s, b)) = log Γ(1 + s) + log Γ(1 + b) - log Γ(1 + s + b) + log(1 + s/b), whose terms are small:
93
+ * log B(s, b) and log s are each about -log s (523 at s = 3e-228), and their difference would keep an error of 1e-13
71
94
  */
72
95
  function betaKernelIncLog(s, b, xd, xcd) {
73
96
  if (!(xd[0] > 0 && xcd[0] > 0))
74
97
  return -Infinity;
75
98
  const l = ddAdd(ddMulNum(ddLog(xd), s), ddMulNum(ddLog(xcd), b));
99
+ if (s < 1 && b < 1)
100
+ return ddAdd(l, [-(lgamma1p(s) + lgamma1p(b) - lgamma1p(s + b) + Math.log1p(s / b)), 0]);
76
101
  return ddAdd(ddAdd(l, ddNeg(lbetaDD(s, b))), [-Math.log(s), 0]);
77
102
  }
78
103
  /** Form x and 1 - x as a double-double pair, based on the smaller of the two */
@@ -80,19 +105,67 @@ function pair(x) {
80
105
  return x <= 0.5 ? [[x, 0], twoSum(1, -x)] : [twoSum(1, -(1 - x)), [1 - x, 0]];
81
106
  }
82
107
  /** One-sided probability (P[X <= x] if lower). 0 < x < 1 */
83
- function pnbetaRaw(a, b, ncp, xd, xcd, lower, log) {
84
- const kernel = betaKernel(a, b, xd, xcd);
108
+ function pnbetaRaw(a, b, ncp, xd, xcd, lower, log, o = odds(xd, xcd)) {
109
+ const m = method(a, b, ncp);
110
+ if (m !== "mixture") {
111
+ const left = leftTailLog(a, b, ncp, xd, xcd);
112
+ if (left !== undefined) {
113
+ if (lower)
114
+ return log ? left : Math.exp(left);
115
+ return log ? Math.log1p(-Math.exp(left)) : -Math.expm1(left);
116
+ }
117
+ return extremeTail(m, a, b, ncp, o, lower, log);
118
+ }
119
+ // A value near 1, and its log, are built from the small value of the other side (the lower tail is likely the smaller
120
+ // below the mean of Beta(a + λ/2, b))
121
+ const v = mixtureTail(ncp / 2, betaKernel(a, b, xd, xcd), lower, xd[0] < (a + ncp / 2) / (a + ncp / 2 + b));
122
+ return log ? v.log : v.lin;
123
+ }
124
+ /**
125
+ * log P[X <= x] far in the left tail for a large λ, as -λ/2 + log S, S = Σ_j (λ/2)^j / j! I_x(a + j, b) (the mixture
126
+ * with e^(-λ/2) taken out of the weights). The terms fall by factors of about r/(j + 1) once j > r, with
127
+ * r = (λ/2) ρ, ρ = x max(1, (a + b)/(a + 1)) (bounding I_x(s + 1, b)/I_x(s, b)), so for r <= 100 the sum takes at most a
128
+ * few hundred terms. Beyond that, S lies between its first term I_x(a, b) and I_x(a, b) e^r: where ρ <= 1e-16 the
129
+ * first term alone gives log P to 1e-16 of λ/2 (and so of |log P|). Undefined otherwise, or for shapes out of the
130
+ * central incomplete beta function's range. (The integral, at log P near -λ/2 = -1e27, cannot place its mode on values
131
+ * that are all -λ/2 to the double)
132
+ */
133
+ function leftTailLog(a, b, ncp, xd, xcd) {
85
134
  const mu = ncp / 2;
86
- const v = mixtureCdf(mu, kernel, lower, false);
87
- if (!log)
88
- return v;
89
- // The log of a value near 1 is built with log1p from the small value of the other side
90
- if (v > 0.5)
91
- return Math.log1p(-mixtureCdf(mu, kernel, !lower, false));
92
- return v >= 1e-280 ? Math.log(v) : mixtureCdf(mu, kernel, lower, true);
135
+ const rho = xd[0] * Math.max(1, (a + b) / (a + 1));
136
+ if (a > 1e15 || b > 1e15)
137
+ return undefined;
138
+ if (mu * rho > 100)
139
+ return rho <= 1e-16 ? -mu + betaIncDD(a, b, xd, xcd, true, true) : undefined;
140
+ const lmu = Math.log(mu);
141
+ let max = -Infinity;
142
+ const terms = [];
143
+ for (let j = 0; j < 1000; j++) {
144
+ const t = j * lmu - lgamma1p(j) + betaIncDD(a + j, b, xd, xcd, true, true);
145
+ terms.push(t);
146
+ if (t > max)
147
+ max = t;
148
+ else if (t < max + LOG_TOL_SERIES && j > mu * rho)
149
+ break;
150
+ }
151
+ let sum = 0;
152
+ for (const t of terms)
153
+ sum += Math.exp(t - max);
154
+ return -mu + max + Math.log(sum);
93
155
  }
156
+ /** Below this, relative to the largest term, the terms of leftTailLog are negligible (they fall faster than 1/2) */
157
+ const LOG_TOL_SERIES = Math.log(1e-18);
94
158
  /** Σ_j w_j e_j (a + j) / divisor. For the density, divisor = x (1 - x) (beta) or q (F) */
95
- function densitySum(a, b, ncp, xd, xcd, divisor, log) {
159
+ function densitySum(a, b, ncp, xd, xcd, divisor, log, o = odds(xd, xcd)) {
160
+ const m = method(a, b, ncp);
161
+ if (m !== "mixture") {
162
+ // The sum is f(x) x (1 - x) / divisor
163
+ // (log x (1 - x) from log(1 - x) where 1 - x is below the double range)
164
+ const xx = ddMul(xd, xcd);
165
+ const lxx = xcd[0] > 1e-300 ? Math.log(xx[0] + xx[1]) : Math.log(xd[0] + xd[1]) + o.l1mx;
166
+ const l = extremeDensityLog(m, a, b, ncp, xd, o) + lxx - Math.log(divisor);
167
+ return log ? l : Math.exp(l);
168
+ }
96
169
  const mu = ncp / 2;
97
170
  const x = xd[0];
98
171
  // The peak is at the j where the term ratio mu x (a + b + j - 1) / (j (a + j - 1)) equals 1
@@ -101,6 +174,380 @@ function densitySum(a, b, ncp, xd, xcd, divisor, log) {
101
174
  const jStar = (-p + Math.sqrt(Math.max(0, p * p + 4 * c * (a + b - 1)))) / 2;
102
175
  return mixtureDensity(mu, betaKernel(a, b, xd, xcd), (j) => a + j, jStar, divisor, log);
103
176
  }
177
+ // ---- Extreme parameters ----
178
+ // X = Y / (Y + W) with Y ~ χ²(2a, λ) and W ~ χ²(2b) independent. Where the mixture would need too many terms (a huge
179
+ // λ, or a huge b against a + λ: its peak is near j = sqrt(λ x b / 2)), and where the central incomplete beta function
180
+ // of its components is out of its range (huge shapes), the distribution is computed from that of Y and W instead.
181
+ // Far in the left tail of a large λ the mixture is summed with e^(-λ/2) taken out of its weights (leftTailLog), and for
182
+ // a λ so large that log P = -(λ/2)(1 - x) to the double, that is the answer (farLeftLog).
183
+ /** Above this mean of the Poisson weights the mixture (at least 10 sqrt(λ/2) terms) is replaced by an integral */
184
+ const MU_MIXTURE = 1e6;
185
+ /**
186
+ * How the distribution is computed:
187
+ * - "chisq": b > 1e20 (a + j)² over the Poisson range of j. Then I_x(a + j, b) = P(a + j, -b log(1 - x)) to
188
+ * O((a + j)²/b) (in t = -b log(1 - X) the density of Beta(s, b) is (1 - e^(-t/b))^(s-1) e^-t up to a constant), so
189
+ * P[X <= x] = P[Y <= -2b log(1 - x)]
190
+ * - "gamma": Y is nearly constant on the scale of the gamma function below (its relative spread 2 sqrt(a + λ)/(2a + λ)
191
+ * is below 1e-4 / S, S = 40 sqrt(b) + 750 bounding |d log P(b, t)/d log t| where P is above the double range), so
192
+ * P[X > x] = P[W < Y k] = E P(b, T), T = Y k/2, k = (1 - x)/x, is P(b, t0) plus its expansion in the cumulants of T
193
+ * about t0 = E T (gammaExpansion)
194
+ * - "w": W is nearly constant on the scale of the distribution function F of Y (its relative spread 1/sqrt(b) is below
195
+ * 1e-5 / S, S = 40 m/σ + 750 bounding |d log F/d log y| likewise, m = 2a + λ, σ = 2 sqrt(a + λ)), so
196
+ * P[X <= x] = P[Y <= W/k] = E F(W/k) = F(y0) + (2b/k²) F''(y0) + ..., y0 = E W/k = 2b/k (the next term, with the
197
+ * third cumulant of W, is below 1e-15 of F)
198
+ * - "integral": a large λ or a huge shape otherwise (integralLog)
199
+ */
200
+ function method(a, b, ncp) {
201
+ const mu = ncp / 2;
202
+ const s = a + mu + 10 * Math.sqrt(mu) + 10;
203
+ if (b > 1e20 * s * s)
204
+ return "chisq";
205
+ if (2 * Math.sqrt(a + ncp) * (40 * Math.sqrt(b) + 750) < 1e-4 * (2 * a + ncp))
206
+ return "gamma";
207
+ if ((40 * (2 * a + ncp)) / (2 * Math.sqrt(a + ncp)) + 750 < 1e-5 * Math.sqrt(b))
208
+ return "w";
209
+ // (shapes above 1e15 are out of the range of the central incomplete beta function: it does not return for
210
+ // a = 1.7e32, b = 6e-35 at a tiny x)
211
+ return mu > MU_MIXTURE || a > 1e15 || b > 1e15 ? "integral" : "mixture";
212
+ }
213
+ /** -log(1 - x) from the pair (x, 1 - x) */
214
+ function minusLog1mx(xd, xcd) {
215
+ return xd[0] <= 0.5 ? -Math.log1p(-(xd[0] + xd[1])) : -(Math.log(xcd[0]) + xcd[1] / xcd[0]);
216
+ }
217
+ /** (1 - x)/x from the pair */
218
+ function oddsInverse(xd, xcd) {
219
+ const r = ddDiv(xcd, xd);
220
+ return r[0] + r[1];
221
+ }
222
+ function odds(xd, xcd) {
223
+ const k = oddsInverse(xd, xcd);
224
+ const lk = k > 1e-300 && k < 1e300 ? Math.log(k) : Math.log(xcd[0]) - Math.log(xd[0]);
225
+ return { k, lk, l1mx: -minusLog1mx(xd, xcd) };
226
+ }
227
+ /** c k, also where k is out of the double range */
228
+ function timesK(c, o) {
229
+ return o.k > 1e-300 && o.k < 1e300 ? c * o.k : Math.exp(Math.log(c) + o.lk);
230
+ }
231
+ /**
232
+ * log g_b(t), the Gamma(b, 1) density, at t = t0 e^v (v = 0 but for the integrals over log y, where the offset is
233
+ * exact; log t0 given where t0 underflows). For b > 1e4 as
234
+ * b (log(1 + d) - d) - log t + log(b/(2 pi))/2 - 1/(12b) + 1/(360b³), d = t/b - 1,
235
+ * with t - b = (t0 - b) + t0 (e^v - 1) (Stirling's series for log Γ(b), whose next term is below 1e-23): the density's
236
+ * helpers overflow for b or t near 1e300 and break down where t/b underflows, and the rounding of t would carry an
237
+ * error of eps sqrt(b) into the log near the mode. For smaller b the log is dominated by -t or -log Γ(b) where t/b or
238
+ * b/t is beyond 1e300 (or t underflows), and is taken from (b - 1) log t - t - log Γ(b) directly; for a tiny b as
239
+ * log b + (b - 1) log t - t - log Γ(1 + b) (dgamma1 is Infinity at b = 1.9e-199)
240
+ */
241
+ function gammaDensityLog(t0, b, v = 0, logT0 = Math.log(t0)) {
242
+ const logT = logT0 + v;
243
+ const t = v === 0 ? t0 : Math.exp(logT);
244
+ if (b > 1e4) {
245
+ const d = (t0 - b + t0 * Math.expm1(v)) / b;
246
+ return b * log1pmx(d) - logT + 0.5 * Math.log(b / (2 * Math.PI)) - 1 / (12 * b) + 1 / (360 * b * b * b);
247
+ }
248
+ if (b < 1e-10)
249
+ return Math.log(b) + (b - 1) * logT - t - lgamma1p(b);
250
+ if (!(t > 1e-300) || t > 1e300 * b || b > 1e300 * t)
251
+ return (b - 1) * logT - t - lgamma(b);
252
+ return dgamma1(t, b, 1, true);
253
+ }
254
+ /**
255
+ * P(b, t) (lower) or Q(b, t), the distribution function of W/2 (its log if log), at t = t0 e^v (as gammaDensityLog).
256
+ * Below t = 1e-300 (where t may have underflowed) from the first term of the series, P(b, t) = t^b / Γ(1 + b) (1 + O(t))
257
+ */
258
+ function gammaTail(b, t0, lower, log, v = 0, logT0 = Math.log(t0)) {
259
+ const logT = logT0 + v;
260
+ const t = v === 0 ? t0 : Math.exp(logT);
261
+ if (t < 1e-300) {
262
+ const lp = b * logT - lgamma1p(b);
263
+ if (lower)
264
+ return log ? lp : Math.exp(lp);
265
+ // (for a tiny b, P is near 1 and Q = -expm1(lp) small)
266
+ return log ? (lp > -Math.LN2 ? Math.log(-Math.expm1(lp)) : Math.log1p(-Math.exp(lp))) : -Math.expm1(lp);
267
+ }
268
+ // (gammaInc takes 40 ms at b = 1e12, t < b, and 0.1 s at b = 1e37)
269
+ if (b > 1e4)
270
+ return gammaTailNear(b, t0, v, lower, log);
271
+ // Both tails, and the log, from the linear value of the small tail, so that they are consistent (gammaInc's log of
272
+ // a tail can differ from the log of its linear value by 4e-14 relative at a tiny t). The lower tail is the small one
273
+ // below about the median, which is far below b for a tiny b (P(1e-9, 1e-14) = 1 - 3e-8), so it is tried first
274
+ const lowerP = gammaInc(b, t, true, false);
275
+ const small = lowerP <= 0.5;
276
+ const p = small ? lowerP : gammaInc(b, t, false, false);
277
+ if (small !== lower)
278
+ return log ? Math.log1p(-p) : 1 - p;
279
+ if (!log)
280
+ return p;
281
+ return p > 1e-300 ? Math.log(p) : gammaInc(b, t, lower, true);
282
+ }
283
+ /** P[X <= x] (lower) / P[X > x] (its log if log) by the method (not "mixture") */
284
+ function extremeTail(m, a, b, ncp, o, lower, log) {
285
+ if (m === "chisq")
286
+ return pnchisq1(-2 * b * o.l1mx, 2 * a, ncp, lower, log);
287
+ const far = farLeftLog(a, b, ncp, o);
288
+ if (far !== undefined) {
289
+ if (lower)
290
+ return log ? far : 0;
291
+ return log ? -0 : 1;
292
+ }
293
+ const expansion = m === "gamma" ? gammaExpansion(a, b, ncp, o, !lower, log) : m === "w" ? wExpansion(a, b, ncp, o, lower, log) : undefined;
294
+ if (expansion !== undefined)
295
+ return expansion;
296
+ const l = integralTailLog(a, b, ncp, o.lk, lower);
297
+ if (l > -Math.LN2) {
298
+ // The integral is accurate relative to itself: a value near 1 is built from the small value of the other side
299
+ // (unless that integral fails, as it can for a tiny shape, where the integrand is flat towards y = 0)
300
+ const other = Math.exp(integralTailLog(a, b, ncp, o.lk, !lower));
301
+ if (other <= 0.5)
302
+ return log ? Math.log1p(-other) : 1 - other;
303
+ }
304
+ return log ? l : Math.exp(l);
305
+ }
306
+ /**
307
+ * log P[X <= x] for a λ so large that its leading term -(λ/2)(1 - x) is all of it to the double: undefined otherwise.
308
+ * X <= x is Y <= W x/(1 - x); with log P[Y <= y] = -(sqrt(λ) - sqrt(y))²/2 and log f_W(w) = -w/2 to leading order,
309
+ * the largest term over w is -(λ/2)(1 - x) (at w = λ x (1 - x)), and the rest, from the powers of y and w and the
310
+ * width of the maximum, is of order (a + b + 1) log λ. (The integral cannot place its mode on values that are all
311
+ * -1e295 to the double, and the expansions in the cumulants of Y fail this far out)
312
+ */
313
+ function farLeftLog(a, b, ncp, o) {
314
+ const mu = ncp / 2;
315
+ if (!(mu > 1e18))
316
+ return undefined;
317
+ // (λ/2)(1 - x): from log(1 - x) where it is near 0, else as (λ/2) k/(1 + k) (k is then below e)
318
+ const lead = o.l1mx > -1 ? mu * Math.exp(o.l1mx) : timesK(mu, o) / (1 + o.k);
319
+ return lead >= 1e17 * (a + b + 1) * (Math.log(mu) + 50) ? -lead : undefined;
320
+ }
321
+ /** log P[X <= x] (lower) / log P[X > x] by integralLog, for log k = log((1 - x)/x) */
322
+ function integralTailLog(a, b, ncp, logK, lower) {
323
+ // X <= x is W >= Y k
324
+ // (towards y = 0 the integrand goes as y^a, or y^(a + b) where P[W < y k] ~ (y k/2)^b / Γ(b + 1))
325
+ const lk = logK - Math.LN2;
326
+ const h = (u0, v) => gammaTail(b, Math.exp(u0 + lk), !lower, true, v, u0 + lk) + u0 + v;
327
+ return integralLog(a, ncp, h, b, lower ? a : a + b);
328
+ }
329
+ /** log f(x) by the method (not "mixture") */
330
+ function extremeDensityLog(m, a, b, ncp, xd, o) {
331
+ const x = xd[0] + xd[1];
332
+ if (m === "chisq") {
333
+ // f(x) = f_Y(2t) 2b/(1 - x), t = -b log(1 - x)
334
+ return dnchisq1(-2 * b * o.l1mx, 2 * a, ncp, true) + Math.log(2 * b) - o.l1mx;
335
+ }
336
+ // f(x) = E[g_b(T) T] / (k x²), g_b the Gamma(b, 1) density (the derivative of E P(b, T) with dk/dx = -1/x²),
337
+ // expanded to second order about t0
338
+ if (m === "gamma") {
339
+ const t0 = timesK(a + ncp / 2, o);
340
+ // v (h² + h' + 2h/t) with h = (b - 1)/t - 1, written as in gammaExpansion (H = b - 1 - t0)
341
+ const H = b - 1 - t0;
342
+ const c = ((a + ncp) / (a + ncp / 2) / (a + ncp / 2)) * (H * H - (b - 1) + 2 * H);
343
+ if (Math.abs(c) < 1e-3)
344
+ return gammaDensityLog(t0, b) + Math.log(a + ncp / 2) + Math.log1p(c / 2) - 2 * Math.log(x);
345
+ }
346
+ // f(x) = E[f_Y(W/k) W] / (k² x²), to zeroth order f_Y(y0) y0 / (k x²) (relative error below 1e-10)
347
+ if (m === "w") {
348
+ const y0 = timesK(2 * b, { k: 1 / o.k, lk: -o.lk, l1mx: NaN });
349
+ return dnchisq1(y0, 2 * a, ncp, true) + Math.log(y0) - o.lk - 2 * Math.log(x);
350
+ }
351
+ // f(x) = ∫ f_Y(y) f_W(y k) y/x² dy
352
+ const lk = o.lk - Math.LN2;
353
+ const h = (u0, v) => gammaDensityLog(Math.exp(u0 + lk), b, v, u0 + lk) - Math.LN2 + 2 * (u0 + v);
354
+ return integralLog(a, ncp, h, b, a + b) - 2 * Math.log(x);
355
+ }
356
+ /**
357
+ * E P(b, T) (lower) or E Q(b, T) for T = Y k/2 (its log if log), by the expansion about t0 = E T = (a + λ/2) k in the
358
+ * cumulants of T (variance v = (a + λ) k², third and fourth cumulants (2a + 3λ) k³ and 6 (a + 2λ) k⁴, from those of
359
+ * the noncentral χ²: 2(n + 2λ), 8(n + 3λ), 48(n + 4λ) with n = 2a):
360
+ * E P(b, T) = P(t0) + v P''/2 + κ3 P'''/6 + (κ4 + 3v²) P''''/24 + ...,
361
+ * with P' = g, P'' = g h, P''' = g (h² - (b - 1)/t²), P'''' = g (h³ - 3h (b - 1)/t² + 2(b - 1)/t³), h = (b - 1)/t - 1.
362
+ * The terms fall by factors of the relative spread of Y times |d log P/d log t| (below 1e-4 by "gamma"), so the
363
+ * error is below 1e-20. Undefined where the correction is not small (|d log P/d log t| larger in a far tail)
364
+ */
365
+ function gammaExpansion(a, b, ncp, o, lower, log) {
366
+ const t0 = timesK(a + ncp / 2, o);
367
+ const base = gammaTail(b, t0, lower, log);
368
+ // The choice of the method bounds |d log G/d log t| by 40 sqrt(b) + 750 where G is in the double range; on the log
369
+ // scale G goes beyond, into the tail of G where that is about |t0 - b| (log Q(b, t) is about -t for t >> b)
370
+ const farTail = (lower ? t0 < b : t0 > b) && Math.abs(t0 - b) > 40 * Math.sqrt(b) + 750;
371
+ if (log) {
372
+ // On the log scale the correction is about (v/2) (L'² + L'') (v = (a + λ) k² the variance of T, L = log G), with
373
+ // |L'| at most 1 but far in the tail of G, where log G is nearly linear in t: L' = b/t - 1 for P (t << b),
374
+ // (b - 1)/t - 1 for Q (t >> b). Where that is below 1e-16 of |log G| (its rounding), log G(b, t0) is the answer;
375
+ // far in the tail it is added while the next term, κ3 L'³/6 (κ3 = (2a + 3λ) k³), is below that. (The terms below
376
+ // could not be formed from logs as large as 1e110)
377
+ const c = lower ? b : b - 1;
378
+ const l1 = farTail ? c / t0 - 1 : 1;
379
+ const v = timesK(timesK(a + ncp, o), o);
380
+ if ((v * Math.max(1, l1 * l1)) / 2 <= 1e-16 * Math.abs(base))
381
+ return base;
382
+ const k3 = timesK(timesK(timesK(2 * a + 3 * ncp, o), o), o);
383
+ if (farTail && (k3 * Math.abs(l1 * l1 * l1)) / 6 <= 1e-16 * Math.abs(base))
384
+ return base + (v / 2) * (l1 * l1 - c / t0 / t0);
385
+ }
386
+ // Far enough out (beyond the bound above) the expansion no longer holds, but for the linear value the log above may
387
+ const spreadT = (2 * Math.sqrt(a + ncp)) / (2 * a + ncp);
388
+ if (farTail && !(spreadT * Math.abs(t0 - b) < 1e-4)) {
389
+ const l = log ? undefined : gammaExpansion(a, b, ncp, o, lower, true);
390
+ return l === undefined ? undefined : Math.exp(l);
391
+ }
392
+ // (t0 times the ratio of the density to the tail, d log G/d log t, which stays of order b where t0 underflows and the
393
+ // ratio itself overflows; 0 far in the other tail, where the moments below can overflow)
394
+ const lgt = gammaDensityLog(t0, b) + Math.log(t0);
395
+ const ratio = log ? Math.exp(lgt - base) : base > 0 ? Math.exp(lgt) / base : 0;
396
+ if (!(t0 > 0 && t0 < Infinity) || ratio === 0)
397
+ return base;
398
+ // In terms of H = h t0 = b - 1 - t0, B = b - 1 and the cumulants relative to A^n (A = a + λ/2, t0 = A k), which do
399
+ // not underflow or overflow where the cumulants themselves do: v h/2 = (w/2) t0 H, w = (a + λ)/A², and so on
400
+ const A = a + ncp / 2;
401
+ const w = (a + ncp) / A / A;
402
+ const u3 = (2 * a + 3 * ncp) / A / A / A;
403
+ const u4 = (6 * (a + 2 * ncp)) / A / A / A / A;
404
+ const H = b - 1 - t0;
405
+ const B = b - 1;
406
+ const series = (w / 2) * H + (u3 / 6) * (H * H - B) + ((u4 + 3 * w * w) / 24) * (H * H * H - 3 * H * B + 2 * B);
407
+ // The correction relative to the tail (P or Q = 1 - P, whose derivatives are those of P negated)
408
+ const rel = (lower ? 1 : -1) * ratio * series;
409
+ if (!(Math.abs(rel) < 1e-3))
410
+ return undefined;
411
+ return log ? base + Math.log1p(rel) : base * (1 + rel);
412
+ }
413
+ /**
414
+ * E F(W/k) (lower) or E (1 - F(W/k)) (its log if log) for the method "w": F(y0) plus (2b/k²) f'(y0) (Var W = 4b, the
415
+ * second derivative of F is f'), with f' from a central difference of log f. Undefined where the correction is not
416
+ * small
417
+ */
418
+ function wExpansion(a, b, ncp, o, lower, log) {
419
+ const y0 = timesK(2 * b, { k: 1 / o.k, lk: -o.lk, l1mx: NaN });
420
+ const base = pnchisq1(y0, 2 * a, ncp, lower, log);
421
+ if (!(y0 > 0 && y0 < Infinity))
422
+ return base;
423
+ const h = 1e-6;
424
+ const dlogf = (dnchisq1(y0 * (1 + h), 2 * a, ncp, true) - dnchisq1(y0 * (1 - h), 2 * a, ncp, true)) / (2 * h * y0);
425
+ const lf = dnchisq1(y0, 2 * a, ncp, true);
426
+ const ratio = log ? Math.exp(lf - base) : base > 0 ? Math.exp(lf) / base : 0;
427
+ const rel = (lower ? 1 : -1) * timesK(y0, { k: 1 / o.k, lk: -o.lk, l1mx: NaN }) * ratio * dlogf;
428
+ if (!(Math.abs(rel) < 1e-3))
429
+ return undefined;
430
+ return log ? base + Math.log1p(rel) : base * (1 + rel);
431
+ }
432
+ /** Ends of the integrals in u = log y: the logs of the smallest and the largest positive doubles */
433
+ const U_MIN = -744;
434
+ const U_MAX = 709.78;
435
+ /**
436
+ * log ∫ exp(L(u)) du over u = log y, L(u) = log f_Y(y) + h(u) (Y ~ χ²(2a, λ)), for an h that makes the integrand
437
+ * unimodal (the log of a distribution function of W at y k, or of its density, plus u or 2u) and that goes as
438
+ * e^(leftSlope u) as y -> 0; h(u0, v) is taken at u0 + v with the offset v exact (as dnchisqLogNear does for f_Y), so
439
+ * that the integrand keeps its accuracy however narrow its peak is in u. The mode is found by a golden-section search,
440
+ * then the integral of exp(L(u) - L(mode)) is taken outwards from it on both sides over intervals of doubling width,
441
+ * each by the adaptive Kronrod rule: upwards until the integrand is below 1e-17 of the sum relative to the rate at
442
+ * which it falls (the secant over the last interval, which overestimates the rest for a log-concave integrand),
443
+ * downwards the same for leftSlope > 1/2, otherwise to the smallest double and the exponential tail beyond. The
444
+ * relative accuracy is that of L(u) - L(mode), about 1e-16 |L(mode)|.
445
+ */
446
+ function integralLog(a, ncp, h, b, leftSlope) {
447
+ // L at u0 + v, with the density of Y and h taken at the exact offset v from y0 = e^u0 (dnchisqLogNear)
448
+ const near = (u0, v) => {
449
+ const l = dnchisqLogNear(Math.exp(u0), v, 2 * a, ncp) + h(u0, v);
450
+ // (the density of Y is infinite at y = 0 for 2a < 2, where y underflows; the integrand y f_Y(y) is not)
451
+ return Number.isNaN(l) || l === Infinity ? -Infinity : l;
452
+ };
453
+ const L = (u) => near(u, 0);
454
+ // Golden-section search for the mode. Far from the mode of Y (about log(2a + λ)) L can be constant to the double
455
+ // (-λ/2 + O(sqrt(λ y)) for y << λ = 1e22); equal values there send the search towards it
456
+ const uy = Math.log(2 * a + ncp);
457
+ const g = (3 - Math.sqrt(5)) / 2;
458
+ let lo = U_MIN;
459
+ let hi = U_MAX;
460
+ let c = lo + g * (hi - lo);
461
+ let d = hi - g * (hi - lo);
462
+ let fc = L(c);
463
+ let fd = L(d);
464
+ // (where L is beyond 1e18 only L(mode) is wanted, to its rounding of 1e-16 |L|: a u to 1e-8 gives that)
465
+ const tol = () => (Math.abs(fc) > 1e18 ? 1e-8 : 1e-14) * Math.max(1, Math.abs(c));
466
+ for (let i = 0; i < 300 && hi - lo > tol(); i++) {
467
+ if (fc > fd || (fc === fd && d > uy)) {
468
+ hi = d;
469
+ d = c;
470
+ fd = fc;
471
+ c = lo + g * (hi - lo);
472
+ fc = L(c);
473
+ }
474
+ else {
475
+ lo = c;
476
+ c = d;
477
+ fc = fd;
478
+ d = hi - g * (hi - lo);
479
+ fd = L(d);
480
+ }
481
+ }
482
+ const [um, lm] = fc >= fd ? [c, fc] : [d, fd];
483
+ // Beyond 1e18 the rounding of L(mode) alone exceeds any log of the integral of exp(L - L(mode)) (the log of a width)
484
+ if (!Number.isFinite(lm) || Math.abs(lm) > 1e18)
485
+ return lm;
486
+ // The integrand at u = mode + t
487
+ const f = (t) => {
488
+ const v = Math.exp(near(um, t) - lm);
489
+ return Number.isFinite(v) ? v : 0;
490
+ };
491
+ // First width: from the curvature at the mode, measured over a step where L falls by about 1 (starting from the
492
+ // spread of log Y or of log W)
493
+ const m = 2 * a + ncp;
494
+ let h0 = Math.min(0.1, (2 * Math.sqrt(a + ncp)) / m, 1 / Math.sqrt(b));
495
+ let fall = 0;
496
+ for (let i = 0; i < 30; i++) {
497
+ fall = 2 * lm - near(um, h0) - near(um, -h0);
498
+ if (fall < 0.01 && h0 < 1)
499
+ h0 *= 10;
500
+ else if (fall > 100)
501
+ h0 /= 10;
502
+ else
503
+ break;
504
+ }
505
+ const w0 = fall > 0 && Number.isFinite(fall) ? h0 / Math.sqrt(fall) : h0;
506
+ let sum = 0;
507
+ // The integrand is known to about eps |L(mode)| (its rounding noise), and costs a density of Y and a gamma function
508
+ const control = quadratureControl(Math.max(1e-15, 4 * Number.EPSILON * Math.abs(lm)), 300);
509
+ // L at the smallest double (computed when needed)
510
+ let lEnd;
511
+ for (const dir of [1, -1]) {
512
+ const end = dir > 0 ? U_MAX - um : um - U_MIN;
513
+ let s0 = 0;
514
+ let w = w0;
515
+ let prev = lm;
516
+ for (let i = 0; i < 200 && s0 < end; i++) {
517
+ const s1 = Math.min(s0 + w, end);
518
+ sum += kronrodAdaptive((t) => f(dir * t), s0, s1, sum, 0, control);
519
+ const l1 = near(um, dir * s1);
520
+ const rate = (prev - l1) / (s1 - s0);
521
+ const rest = rate > 0 ? Math.exp(l1 - lm) / rate : Infinity;
522
+ // For a small leftSlope the integrand can have a second, flat part towards y = 0 (for a = 1e-20 Y has nearly an
523
+ // atom e^(-λ/2) at 0), which the fall of the bulk would hide: there the integral goes on until L follows the
524
+ // power law e^(leftSlope u) down to the smallest double, and the rest is that of the power law
525
+ if ((dir > 0 || leftSlope > 0.5) && rest <= 1e-17 * sum)
526
+ break;
527
+ if (dir < 0 && s1 < end) {
528
+ lEnd ??= near(um, -end);
529
+ // (no flat part where even the power law from the smallest double would be negligible)
530
+ if (rest <= 1e-17 * sum && Math.exp(lEnd - lm) / leftSlope <= 1e-17 * sum)
531
+ break;
532
+ const predicted = l1 - leftSlope * (end - s1);
533
+ if (Number.isFinite(lEnd) && Math.abs(lEnd - predicted) <= 1e-9 * Math.max(1, Math.abs(lEnd))) {
534
+ sum += Math.exp(l1 - lm) / leftSlope;
535
+ break;
536
+ }
537
+ }
538
+ // At the lower end of the range (y below the smallest double) add the rest of the tail, exp(L) falling as
539
+ // e^(leftSlope u) (for a shape of 1e-20 L is constant to the double there, and the rest is most of the integral)
540
+ if (s1 === end && dir < 0)
541
+ sum += Math.exp(l1 - lm) / leftSlope;
542
+ prev = l1;
543
+ s0 = s1;
544
+ w *= 2;
545
+ }
546
+ }
547
+ // (a sum that overflows: the mode was not found, as where L is flat to the double for a tiny shape; -Infinity, the
548
+ // log of the integral from the mode alone being no better)
549
+ return Number.isFinite(sum) ? lm + Math.log(sum) : -Infinity;
550
+ }
104
551
  function validBeta(a, b, ncp) {
105
552
  return a > 0 && b > 0 && Number.isFinite(a) && Number.isFinite(b) && ncp >= 0 && Number.isFinite(ncp);
106
553
  }
@@ -152,6 +599,27 @@ export function pnbeta1(q, a, b, ncp, lowerTail, logP) {
152
599
  const [xd, xcd] = pair(q);
153
600
  return pnbetaRaw(a, b, ncp, xd, xcd, lowerTail, logP);
154
601
  }
602
+ /** The larger of the relative spreads of Y and W, 2 sqrt(a + λ)/(2a + λ) and 1/sqrt(b) */
603
+ function relativeSpread(a, b, ncp) {
604
+ return Math.max((2 * Math.sqrt(a + ncp)) / (2 * a + ncp), 1 / Math.sqrt(b));
605
+ }
606
+ /** The distribution function of a quantile search, remembering its values: the searches come back to the same x */
607
+ function memoCdf(f) {
608
+ const cache = new Map();
609
+ return (x, lower, log) => {
610
+ const key = `${x} ${lower} ${log}`;
611
+ let v = cache.get(key);
612
+ if (v === undefined) {
613
+ v = f(x, lower, log);
614
+ cache.set(key, v);
615
+ }
616
+ return v;
617
+ };
618
+ }
619
+ /** Whether a shape or df is in the range where the central quantile serves as a starting value */
620
+ function inCentralRange(s) {
621
+ return s >= 1e-10 && s <= 1e15;
622
+ }
155
623
  export function qnbeta1(p, a, b, ncp, lowerTail, logP) {
156
624
  if (Number.isNaN(p) || Number.isNaN(a) || Number.isNaN(b) || Number.isNaN(ncp))
157
625
  return NaN;
@@ -166,10 +634,10 @@ export function qnbeta1(p, a, b, ncp, lowerTail, logP) {
166
634
  if (ncp === 0)
167
635
  return qbeta1(p, a, b, lowerTail, logP);
168
636
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
169
- const cdfAt = (x, l, log) => {
637
+ const cdfAt = memoCdf((x, l, log) => {
170
638
  const [xd, xcd] = pair(x);
171
639
  return pnbetaRaw(a, b, ncp, xd, xcd, l, log);
172
- };
640
+ });
173
641
  // If the target is already passed at an end point, the answer is not representable (0 or 1)
174
642
  const atMin = cdfAt(Number.MIN_VALUE, lower, true);
175
643
  if (lower ? atMin >= logTarget : atMin <= logTarget)
@@ -177,11 +645,17 @@ export function qnbeta1(p, a, b, ncp, lowerTail, logP) {
177
645
  const atMax = cdfAt(1 - Number.EPSILON / 2, lower, true);
178
646
  if (lower ? atMax < logTarget : atMax > logTarget)
179
647
  return 1;
180
- // Starting value: quantile of the approximation Beta(a + λ/2, b) (rather than a mean-matched central beta)
181
- let x0 = qbeta1(logTarget, a + ncp / 2, b, lower, true);
648
+ // Starting value: quantile of the approximation Beta(a + λ/2, b) (rather than a mean-matched central beta); its
649
+ // mean where the shapes are out of the central quantile's range
650
+ const central = method(a, b, ncp) === "mixture" && inCentralRange(a) && inCentralRange(b);
651
+ let x0 = central ? qbeta1(logTarget, a + ncp / 2, b, lower, true) : (a + ncp / 2) / (a + ncp / 2 + b);
182
652
  if (!(x0 > 0 && x0 < 1))
183
653
  x0 = 0.5;
184
- return invertContinuous({
654
+ const passes = (x) => (lower ? cdfAt(x, true, true) >= logTarget : cdfAt(x, false, true) <= logTarget);
655
+ const narrow = relativeSpread(a, b, ncp) < 1e-10 ? narrowQuantile(x0, 1 - Number.EPSILON / 2, passes) : undefined;
656
+ if (narrow !== undefined)
657
+ return narrow;
658
+ const x = invertContinuous({
185
659
  logTarget,
186
660
  ...(linearTarget !== undefined && { linearTarget }),
187
661
  lower,
@@ -192,12 +666,21 @@ export function qnbeta1(p, a, b, ncp, lowerTail, logP) {
192
666
  lo: 0,
193
667
  hi: 1,
194
668
  positive: true,
669
+ maxIter: 60,
195
670
  });
671
+ const search = () => searchDoubles(x, Number.MIN_VALUE, 1 - Number.EPSILON / 2, passes);
672
+ return confirmQuantile(x, cdfAt(x, lower, true), logTarget, search, passes);
196
673
  }
197
674
  // ---- Noncentral F ----
198
675
  /** x = m q/(n + m q) and 1 - x = n/(n + m q) in double-double */
199
676
  function fPair(q, m, n) {
200
677
  const mq = twoProd(m, q);
678
+ if (mq[0] < 1e-290) {
679
+ // m q underflows (a tiny m) where m q/n need not: x = r/(1 + r), 1 - x = 1/(1 + r), r = (m/n) q
680
+ const r = ddMul(ddDiv([m, 0], [n, 0]), [q, 0]);
681
+ const d = ddAdd(r, [1, 0]);
682
+ return [ddDiv(r, d), ddDiv([1, 0], d)];
683
+ }
201
684
  if (Number.isFinite(mq[0]) && Number.isFinite(mq[1]) && Math.abs(mq[0]) < 1e290) {
202
685
  const d = ddAdd(mq, [n, 0]);
203
686
  return [ddDiv(mq, d), ddDiv([n, 0], d)];
@@ -205,6 +688,15 @@ function fPair(q, m, n) {
205
688
  const zc = n / m / q;
206
689
  return [twoSum(1, -zc), [zc, 0]];
207
690
  }
691
+ /** The Odds of x = m q/(n + m q): k = n/(m q), from its logs where it is out of the double range */
692
+ function fOdds(q, m, n, xd, xcd) {
693
+ const o = odds(xd, xcd);
694
+ if (!(o.k < 1e-300))
695
+ return o;
696
+ const k = n / m / q;
697
+ const lk = Math.log(n) - Math.log(m) - Math.log(q);
698
+ return { k, lk, l1mx: lk - Math.log1p(k) };
699
+ }
208
700
  function dnfCore(q, m, n, ncp, log) {
209
701
  if ((m / n) * q < 1e-306) {
210
702
  // First term of the series: f(q) ≈ exp(-λ/2) (m q / n)^a / (B(a, b) q)
@@ -213,7 +705,7 @@ function dnfCore(q, m, n, ncp, log) {
213
705
  return log ? l : Math.exp(l);
214
706
  }
215
707
  const [xd, xcd] = fPair(q, m, n);
216
- return densitySum(m / 2, n / 2, ncp, xd, xcd, q, log);
708
+ return densitySum(m / 2, n / 2, ncp, xd, xcd, q, log, fOdds(q, m, n, xd, xcd));
217
709
  }
218
710
  /**
219
711
  * q so small that x = m q/(n + m q) underflows: first term of the series
@@ -224,13 +716,13 @@ function pnfTiny(q, m, n, ncp, lower, log) {
224
716
  const l = -ncp / 2 + a * (Math.log(m / n) + Math.log(q)) - Math.log(a) - lbeta(a, n / 2);
225
717
  if (lower)
226
718
  return log ? l : Math.exp(l);
227
- return log ? -Math.exp(l) : -Math.expm1(l);
719
+ return log ? Math.log1p(-Math.exp(l)) : -Math.expm1(l);
228
720
  }
229
721
  export function pnfRaw(q, m, n, ncp, lower, log) {
230
722
  if ((m / n) * q < 1e-306)
231
723
  return pnfTiny(q, m, n, ncp, lower, log);
232
724
  const [xd, xcd] = fPair(q, m, n);
233
- return pnbetaRaw(m / 2, n / 2, ncp, xd, xcd, lower, log);
725
+ return pnbetaRaw(m / 2, n / 2, ncp, xd, xcd, lower, log, fOdds(q, m, n, xd, xcd));
234
726
  }
235
727
  export function dnf1(x, m, n, ncp, log) {
236
728
  if (Number.isNaN(x) || Number.isNaN(m) || Number.isNaN(n) || Number.isNaN(ncp))
@@ -302,8 +794,9 @@ function fTailBound(q, m, n, ncp) {
302
794
  const c = (q * m) / n;
303
795
  if (!(c > 0 && Number.isFinite(c)))
304
796
  return undefined;
305
- const lower = (s) => -(m / 2) * Math.log1p(2 * s) - (ncp * s) / (1 + 2 * s) - (n / 2) * Math.log1p(-2 * c * s);
306
- const upper = (s) => -(m / 2) * Math.log1p(-2 * s) + (ncp * s) / (1 - 2 * s) - (n / 2) * Math.log1p(2 * c * s);
797
+ // (c s formed first: 2c overflows for q near the largest double)
798
+ const lower = (s) => -(m / 2) * Math.log1p(2 * s) - (ncp * s) / (1 + 2 * s) - (n / 2) * Math.log1p(-2 * (c * s));
799
+ const upper = (s) => -(m / 2) * Math.log1p(-2 * s) + (ncp * s) / (1 - 2 * s) - (n / 2) * Math.log1p(2 * (c * s));
307
800
  const best = (f, sMax) => {
308
801
  let b = Infinity;
309
802
  for (let i = 1; i <= 60; i++) {
@@ -337,27 +830,37 @@ export function qnf1(p, m, n, ncp, lowerTail, logP) {
337
830
  }
338
831
  function qnfRaw(p, m, n, ncp, lowerTail, logP) {
339
832
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
340
- const atMin = pnfRaw(Number.MIN_VALUE, m, n, ncp, lower, true);
833
+ const cdfAt = memoCdf((x, l, log) => pnfRaw(x, m, n, ncp, l, log));
834
+ const atMin = cdfAt(Number.MIN_VALUE, lower, true);
341
835
  if (lower ? atMin >= logTarget : atMin <= logTarget)
342
836
  return 0;
343
- const atMax = pnfRaw(Number.MAX_VALUE, m, n, ncp, lower, true);
837
+ const atMax = cdfAt(Number.MAX_VALUE, lower, true);
344
838
  if (lower ? atMax < logTarget : atMax > logTarget)
345
839
  return Infinity;
346
- // Starting value: Patnaik's approximation (m + λ)/m F(ν, n), ν = (m + λ)^2/(m + 2λ)
347
- const nu = ((m + ncp) * (m + ncp)) / (m + 2 * ncp);
348
- let x0 = ((m + ncp) / m) * qf1(logTarget, nu, n, lower, true);
840
+ // Starting value: Patnaik's approximation (m + λ)/m F(ν, n), ν = (m + λ)^2/(m + 2λ); (m + λ)/m (the ratio of the
841
+ // means of the χ² variables per degree of freedom) where the parameters are out of the central quantile's range
842
+ const nu = (m + ncp) * ((m + ncp) / (m + 2 * ncp));
843
+ const central = method(m / 2, n / 2, ncp) === "mixture" && inCentralRange(m) && inCentralRange(n);
844
+ let x0 = ((m + ncp) / m) * (central ? qf1(logTarget, nu, n, lower, true) : 1);
349
845
  if (!(x0 > 0) || !Number.isFinite(x0))
350
846
  x0 = 1;
351
- return invertContinuous({
847
+ const passes = (x) => (lower ? cdfAt(x, true, true) >= logTarget : cdfAt(x, false, true) <= logTarget);
848
+ const narrow = relativeSpread(m / 2, n / 2, ncp) < 1e-10 ? narrowQuantile(x0, Number.MAX_VALUE, passes) : undefined;
849
+ if (narrow !== undefined)
850
+ return narrow;
851
+ const x = invertContinuous({
352
852
  logTarget,
353
853
  ...(linearTarget !== undefined && { linearTarget }),
354
854
  lower,
355
- cdf: (x, l) => pnfRaw(x, m, n, ncp, l, false),
356
- cdfLog: (x, l) => pnfRaw(x, m, n, ncp, l, true),
855
+ cdf: (x, l) => cdfAt(x, l, false),
856
+ cdfLog: (x, l) => cdfAt(x, l, true),
357
857
  pdfLog: (x) => dnfCore(x, m, n, ncp, true),
358
858
  x0,
359
859
  lo: 0,
360
860
  hi: Infinity,
361
861
  positive: true,
862
+ maxIter: 60,
362
863
  });
864
+ const search = () => searchDoubles(x, Number.MIN_VALUE, Number.MAX_VALUE, passes);
865
+ return confirmQuantile(x, cdfAt(x, lower, true), logTarget, search, passes);
363
866
  }