@numero-uno-jpn/rstats 0.15.1 → 0.15.3

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 (88) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.ja.md +8 -8
  3. package/README.md +8 -8
  4. package/dist/chunks/{chunk-735NNFAS.js → chunk-3THFTB36.js} +2 -2
  5. package/dist/chunks/chunk-3TSWYE5L.js +2 -0
  6. package/dist/chunks/{chunk-7J4HW6VF.js → chunk-3WPU6LGK.js} +2 -2
  7. package/dist/chunks/{chunk-Z3C3G5XI.js → chunk-5ITR67MB.js} +2 -2
  8. package/dist/chunks/chunk-5NRFU6F6.js +2 -0
  9. package/dist/chunks/{chunk-SAZAEPZC.js → chunk-E2LCSVQV.js} +1 -1
  10. package/dist/chunks/chunk-FCNVTIPJ.js +2 -0
  11. package/dist/chunks/chunk-FKAKALOZ.js +2 -0
  12. package/dist/chunks/{chunk-5OSQ76OO.js → chunk-HD73UKPT.js} +2 -2
  13. package/dist/chunks/{chunk-4ILI2FSB.js → chunk-IUULP3LE.js} +1 -1
  14. package/dist/chunks/{chunk-LY2T6DA6.js → chunk-JQG3YQOC.js} +2 -2
  15. package/dist/chunks/chunk-KT66SB7R.js +2 -0
  16. package/dist/chunks/{chunk-IQOVOHZG.js → chunk-MAUAOQG3.js} +2 -2
  17. package/dist/chunks/{chunk-GEJCBCMP.js → chunk-MDYE7QP2.js} +2 -2
  18. package/dist/chunks/{chunk-5SQFDLNG.js → chunk-NM3Z2UBQ.js} +2 -2
  19. package/dist/chunks/{chunk-5XQZNKHZ.js → chunk-PMJI5QO6.js} +2 -2
  20. package/dist/chunks/chunk-UF7KOTHF.js +3 -0
  21. package/dist/chunks/chunk-UOE57JGT.js +2 -0
  22. package/dist/chunks/{chunk-3QTVXDUM.js → chunk-USPEBXSR.js} +2 -2
  23. package/dist/chunks/{chunk-H4CHJMFU.js → chunk-VLUL2HFW.js} +1 -1
  24. package/dist/chunks/{chunk-VOIJKNL2.js → chunk-ZIX7NYQF.js} +1 -1
  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 +75 -2
  29. package/dist/distributions/cauchy.js +76 -5
  30. package/dist/distributions/exponential.js +16 -2
  31. package/dist/distributions/f.js +143 -24
  32. package/dist/distributions/gamma.d.ts +13 -2
  33. package/dist/distributions/gamma.js +122 -12
  34. package/dist/distributions/geometric.js +19 -3
  35. package/dist/distributions/invgamma.js +60 -10
  36. package/dist/distributions/kumaraswamy.js +116 -17
  37. package/dist/distributions/laplace.js +5 -2
  38. package/dist/distributions/logistic.js +8 -2
  39. package/dist/distributions/lognormal.js +40 -5
  40. package/dist/distributions/nbeta.js +597 -52
  41. package/dist/distributions/nchisq.d.ts +25 -0
  42. package/dist/distributions/nchisq.js +381 -96
  43. package/dist/distributions/negbinomial.js +26 -6
  44. package/dist/distributions/normal.js +29 -1
  45. package/dist/distributions/nt.d.ts +28 -3
  46. package/dist/distributions/nt.js +401 -63
  47. package/dist/distributions/pareto.js +73 -19
  48. package/dist/distributions/t.js +102 -12
  49. package/dist/distributions/triangular.js +93 -27
  50. package/dist/distributions/tukey.js +110 -50
  51. package/dist/distributions/uniform.js +14 -9
  52. package/dist/distributions/weibull.js +65 -10
  53. package/dist/distributions.js +2 -2
  54. package/dist/internal/ddexp.d.ts +13 -0
  55. package/dist/internal/ddexp.js +55 -3
  56. package/dist/internal/discrete.js +30 -7
  57. package/dist/internal/invert.d.ts +5 -0
  58. package/dist/internal/invert.js +59 -5
  59. package/dist/internal/noncentral.d.ts +41 -0
  60. package/dist/internal/noncentral.js +124 -2
  61. package/dist/internal/poissonMixture.d.ts +7 -2
  62. package/dist/internal/poissonMixture.js +142 -38
  63. package/dist/linalg.js +2 -2
  64. package/dist/mixed.js +2 -2
  65. package/dist/numerics.js +2 -2
  66. package/dist/rstats.js +14 -14
  67. package/dist/special/beta.js +7 -0
  68. package/dist/special/dd.d.ts +1 -1
  69. package/dist/special/dd.js +4 -1
  70. package/dist/special/gamma.js +4 -0
  71. package/dist/special/igam.js +126 -21
  72. package/dist/special/incbet.d.ts +10 -0
  73. package/dist/special/incbet.js +218 -48
  74. package/dist/special/incbetLargeA.js +53 -14
  75. package/dist/special/incbetPrefactor.d.ts +57 -0
  76. package/dist/special/incbetPrefactor.js +103 -0
  77. package/dist/special/incbetTemme.js +15 -3
  78. package/dist/special/loader.js +97 -22
  79. package/dist/special.js +2 -2
  80. package/dist/tests.js +2 -2
  81. package/package.json +1 -1
  82. package/dist/chunks/chunk-5YMP4WAJ.js +0 -2
  83. package/dist/chunks/chunk-BDJPSEA7.js +0 -2
  84. package/dist/chunks/chunk-KO6QQPC6.js +0 -2
  85. package/dist/chunks/chunk-OLPTFKIZ.js +0 -3
  86. package/dist/chunks/chunk-TYFGVCVQ.js +0 -2
  87. package/dist/chunks/chunk-UWBYDIOH.js +0 -2
  88. package/dist/chunks/chunk-UZHY5DWN.js +0 -2
@@ -20,7 +20,9 @@
20
20
  // When |t| is large and Φ(t S - δ) becomes a steep step relative to the width of the density of w, switch to
21
21
  // formula B, obtained by integrating by parts in v = t S - δ (a peak of φ × the incomplete gamma function; see
22
22
  // the comment on integrate). The far tail with even larger |t| is extrapolated by the power law P ∝ |t|^(-ν)
23
- // (farLimit).
23
+ // (farLimit). For a large ν (a > 1e5) the integral is taken by Laplace's method wherever its neglected terms are below
24
+ // the rounding (laplace); for a small ν (a < 1e-5) formula B is used at any t, and a t so near 0 that P is Φ(-δ) to
25
+ // the double is given that value (nearZero). The smaller tail is computed, the larger is 1 - (smaller).
24
26
  //
25
27
  // For accuracy, the node w and, on top of it, e^(w/2), the exponent a (e^w - 1 - w) and the normal argument
26
28
  // t S - δ are formed in double-double (rounding in each is amplified hundreds of times in the tails). Nodes
@@ -28,11 +30,13 @@
28
30
  // precision (the fast path).
29
31
  import { quantileBoundaries, smallerTail } from "../internal/dpq.js";
30
32
  import { invertContinuous } from "../internal/invert.js";
31
- import { ddAdd, ddMul, ddMulNum, twoSum } from "../special/dd.js";
33
+ import { ddAdd, ddMul, ddMulNum, twoProd, twoSum } from "../special/dd.js";
32
34
  import { erfcxNonNegative } from "../special/erf.js";
33
35
  import { gammaInc } from "../special/igam.js";
34
36
  import { dpoisRaw, stirlerr } from "../special/loader.js";
35
- import { pnorm, qnorm } from "./normal.js";
37
+ import { lgamma1p } from "../special/gamma.js";
38
+ import { qgammaStd } from "./gamma.js";
39
+ import { dnorm, pnorm, qnorm } from "./normal.js";
36
40
  const LN_SQRT_2PI = 0.918938533204672741780329736406;
37
41
  const SQRT_2_PI = 0.7978845608028654; // sqrt(2/pi)
38
42
  const LN2_DD = [0.6931471805599453, 2.3190468138462996e-17];
@@ -88,6 +92,39 @@ function millsInv(z) {
88
92
  return SQRT_2_PI / erfcxNonNegative(-z * Math.SQRT1_2);
89
93
  return Math.exp(-0.5 * z * z - LN_SQRT_2PI) / pnorm(z);
90
94
  }
95
+ /** Below this x = a e^w, P(a, x) = x^a / Γ(1 + a) (1 + O(x)) is taken from log x = log a + w (x may underflow) */
96
+ const X_TINY = 1e-300;
97
+ /** a e^w, also where e^w overflows (a tiny a with |t| tiny takes formula B out to S = |δ|/|t|) */
98
+ function shapeTimesExp(a, w) {
99
+ return w < 700 ? a * Math.exp(w) : Math.exp(Math.log(a) + w);
100
+ }
101
+ /**
102
+ * log G(a, x) at x = a e^w (G = P if lower, Q otherwise) and log(x^a e^-x / Γ(a + 1)) (the derivative of P in log x).
103
+ * For a tiny a the integrals reach x far below the double range, where P(a, x) is still near 1 (x^a = e^(a log x))
104
+ */
105
+ function gammaLog(a, w, lower) {
106
+ const x = shapeTimesExp(a, w);
107
+ if (x > X_TINY) {
108
+ // Q(a, x) = (a/A_SUB) Q(A_SUB, x) (1 + O(A_SUB log x)) for a < A_SUB: at a subnormal a the log of Q, itself near a,
109
+ // lost digits (7e-5 at a = 1e-320)
110
+ if (!lower && a < A_SUB)
111
+ return [gammaInc(A_SUB, x, false, true) + Math.log(a / A_SUB), dpoisRaw(a, x, true)];
112
+ return [gammaInc(a, x, lower, true), dpoisRaw(a, x, true)];
113
+ }
114
+ // log P = a m, m = log x - lgamma1p(a)/a; lgamma1p(a)/a is -γ (1 + O(a)) where lgamma1p(a) would be subnormal
115
+ const m = Math.log(a) + w - (a < A_SUB ? -EULER : lgamma1p(a) / a);
116
+ const lp = a * m;
117
+ if (lower)
118
+ return [lp, lp];
119
+ // log Q = log(-expm1(a m)): log(a) + log(-m) + log1p(lp/2) where a m is so small (it may be subnormal)
120
+ const lq = lp > -1e-10 ? Math.log(a) + Math.log(-m) + Math.log1p(lp / 2) : lp > -Math.LN2 ? Math.log(-Math.expm1(lp)) : Math.log1p(-Math.exp(lp));
121
+ return [lq, lp];
122
+ }
123
+ /** Below this a the upper incomplete gamma function is scaled from Q(A_SUB, x) (gammaLog) */
124
+ const A_SUB = 1e-300;
125
+ const EULER = 0.5772156649015329;
126
+ /** Above this x/(a + 1) the second derivative of log Q(a, x) in w comes from the asymptotic series of Q (logIntegrand) */
127
+ const Q_ASYMPTOTIC = 1e8;
91
128
  /** Log of the integrand (double precision, for locating the peak) and its first and second derivatives */
92
129
  function logIntegrand(pr, w) {
93
130
  const { a, t, delta } = pr;
@@ -98,14 +135,20 @@ function logIntegrand(pr, w) {
98
135
  const m = expm1mxNum(w);
99
136
  if (pr.kind === "cdfQ" || pr.kind === "cdfP") {
100
137
  // log(t S / 2) + log φ(z) + log G(a, x), x = a S^2 = a e^w
101
- const x = a * ew;
138
+ const x = shapeTimesExp(a, w);
102
139
  const upperG = pr.kind === "cdfQ";
103
- const lG = gammaInc(a, x, !upperG, true);
104
- const xf = a * Math.exp(dpoisRaw(a, x, true) - lG); // x f(x) / G
140
+ const [lG, ld] = gammaLog(a, w, !upperG);
141
+ // x f(x) / G (with log a inside the exp: for a subnormal a, f(x)/G alone can overflow)
142
+ const xf = Math.exp(Math.log(a) + ld - lG);
105
143
  const sgn = upperG ? -1 : 1;
106
144
  const L = Math.log(t / 2) + w / 2 - 0.5 * z * z - LN_SQRT_2PI + lG;
107
145
  const d1 = 0.5 - (z * tS) / 2 + sgn * xf;
108
- const d2 = -(tS * tS) / 4 - (z * tS) / 4 + sgn * xf * (a - x) - xf * xf;
146
+ // (for Q, the derivative of -xf is xf (x - a - xf), which cancels where x is large: xf = x/(1 + (a-1)/x + ...),
147
+ // from logs near -x, is off by about eps x relative, the difference by eps x² against its value of about -1. From
148
+ // the asymptotic series of Q, x - a - xf = -1 - (a-1)/x up to O(((a+1)/x)²); with the cancelled form the peak
149
+ // search of formula B for a subnormal a and δ = 1e5 stopped short in steps of 1/x, and the log of pt was +Infinity)
150
+ const d2G = upperG && x > Q_ASYMPTOTIC * (a + 1) ? -xf * (1 + (a - 1) / x) : sgn * xf * (a - x) - xf * xf;
151
+ const d2 = -(tS * tS) / 4 - (z * tS) / 4 + d2G;
109
152
  return [L, d1, d2];
110
153
  }
111
154
  let L = pr.logC - a * m;
@@ -128,8 +171,10 @@ function logIntegrand(pr, w) {
128
171
  function findPeak(pr) {
129
172
  let w = 0;
130
173
  let [L, d1, d2] = logIntegrand(pr, w);
131
- for (let i = 0; i < 200; i++) {
132
- let step = d2 < 0 ? -d1 / d2 : Math.sign(d1);
174
+ // (where L is convex the step is the largest one; for a tiny a the peak of the density can be at w = 800, with L
175
+ // convex most of the way from 0)
176
+ for (let i = 0; i < 400; i++) {
177
+ let step = d2 < 0 ? -d1 / d2 : 4 * Math.sign(d1);
133
178
  if (!Number.isFinite(step))
134
179
  step = Math.sign(d1) || 0;
135
180
  step = Math.max(-4, Math.min(4, step));
@@ -187,8 +232,10 @@ function integrand(pr, w, log, peak = Infinity) {
187
232
  return [v, 0];
188
233
  }
189
234
  else {
190
- const v = base * Math.exp(-0.5 * z * z - LN_SQRT_2PI) * Sd;
191
- if ((Ed + Math.abs(z * tS) + z * z) * v <= 4 * peak)
235
+ // (one exp where C_a e^-E underflows on its own: for a tiny a, C_a is about a, and S can be 1e100)
236
+ const lv = pr.logC - Ed - 0.5 * z * z - LN_SQRT_2PI;
237
+ const v = lv > -700 ? Math.exp(lv) * Sd : Math.exp(lv + wv / 2);
238
+ if ((Ed + Math.abs(z * tS) + z * z + (lv > -700 ? 0 : -lv)) * v <= 4 * peak)
192
239
  return [v, 0];
193
240
  }
194
241
  }
@@ -198,16 +245,18 @@ function integrand(pr, w, log, peak = Infinity) {
198
245
  // (t S / 2) φ(t S - δ) G(a, a S^2)
199
246
  const zd = ddAdd(ddMulNum(S, t), [-delta, 0]);
200
247
  const zz = ddMul(zd, zd);
201
- const x = a * ew[0] + a * ew[1];
248
+ const x = w[0] < 700 ? a * ew[0] + a * ew[1] : shapeTimesExp(a, w[0] + w[1]);
202
249
  const lower = pr.kind === "cdfP";
203
250
  if (log) {
204
- const rest = Math.log(t / 2) + Math.log(S[0]) + S[1] / S[0] - LN_SQRT_2PI + gammaInc(a, x, lower, true);
251
+ const rest = Math.log(t / 2) + Math.log(S[0]) + S[1] / S[0] - LN_SQRT_2PI + gammaLog(a, w[0] + w[1], lower)[0];
205
252
  return ddAdd([-zz[0] / 2, -zz[1] / 2], [rest, 0]);
206
253
  }
207
- const g = gammaInc(a, x, lower, false);
254
+ const g = x > X_TINY ? gammaInc(a, x, lower, false) : Math.exp(gammaLog(a, w[0] + w[1], lower)[0]);
208
255
  return [(t / 2) * (S[0] + S[1]) * Math.exp(-0.5 * zz[0] - LN_SQRT_2PI) * (1 - zz[1] / 2) * g, 0];
209
256
  }
210
- const E = ddMulNum(expm1mx(w, ew), a); // a (e^w - 1 - w)
257
+ // a (e^w - 1 - w); (a tiny a reaches e^w near the overflow threshold, where the splitting in ddMulNum overflows)
258
+ const m = expm1mx(w, ew);
259
+ const E = m[0] < 1e290 ? ddMulNum(m, a) : twoSum(a * m[0], a * m[1]);
211
260
  if (!(E[0] < Infinity))
212
261
  return [log ? -Infinity : 0, 0];
213
262
  const zd = ddAdd(ddMulNum(S, t), [-delta, 0]);
@@ -225,7 +274,10 @@ function integrand(pr, w, log, peak = Infinity) {
225
274
  const l = ddAdd(ddAdd([pr.logC - E[0], -E[1]], [-zz[0] / 2, -zz[1] / 2]), [w[0] / 2 - LN_SQRT_2PI, w[1] / 2]);
226
275
  return l;
227
276
  }
228
- return [Math.exp(pr.logC - E[0] - 0.5 * zz[0] - LN_SQRT_2PI) * (1 - E[1] - zz[1] / 2) * (S[0] + S[1]), 0];
277
+ const lv = pr.logC - E[0] - 0.5 * zz[0] - LN_SQRT_2PI;
278
+ if (lv < -700)
279
+ return [Math.exp(lv + w[0] / 2) * (1 - E[1] - zz[1] / 2 + w[1] / 2), 0];
280
+ return [Math.exp(lv) * (1 - E[1] - zz[1] / 2) * (S[0] + S[1]), 0];
229
281
  }
230
282
  /** Trapezoidal sum (step h in z, extending both ways until negligible) */
231
283
  function trapezoid(pr, w0, sigma, h, log, offset, odd, peak) {
@@ -265,11 +317,22 @@ function trapezoid(pr, w0, sigma, h, log, offset, odd, peak) {
265
317
  return sum;
266
318
  }
267
319
  function integrate(pr, needLog) {
320
+ if (pr.a > A_LAPLACE) {
321
+ const v = laplace(pr);
322
+ if (v !== undefined)
323
+ return v;
324
+ }
268
325
  if (pr.kind === "cdf") {
269
- const pk = findPeak(pr);
270
- const S = Math.exp(pk.w / 2);
271
- const widthW = Math.min(1 / Math.sqrt(pr.a * Math.exp(pk.w)), 10);
272
- if ((Math.abs(pr.t) * S * widthW) / 2 > 2) {
326
+ // (for a tiny a the density of w is spread over w down to about -1/a, and the peak of formula A is not found;
327
+ // formula B is used at any t)
328
+ const pk = pr.a < A_TINY ? undefined : findPeak(pr);
329
+ let formulaB = true;
330
+ if (pk !== undefined) {
331
+ const S = Math.exp(pk.w / 2);
332
+ const widthW = Math.min(1 / Math.sqrt(pr.a * Math.exp(pk.w)), 10);
333
+ formulaB = (Math.abs(pr.t) * S * widthW) / 2 > 2;
334
+ }
335
+ if (formulaB) {
273
336
  if (pr.t > 0) {
274
337
  const r = integrateCore({ ...pr, kind: "cdfQ" }, needLog);
275
338
  return {
@@ -277,12 +340,161 @@ function integrate(pr, needLog) {
277
340
  log: needLog ? logAddExp(pnorm(-pr.delta, { logP: true }), r.log) : NaN,
278
341
  };
279
342
  }
280
- return integrateCore({ ...pr, t: -pr.t, delta: -pr.delta, kind: "cdfP" }, needLog);
343
+ if (pr.a >= A_TINY)
344
+ return integrateCore({ ...pr, t: -pr.t, delta: -pr.delta, kind: "cdfP" }, needLog);
345
+ // E[Φ(t S - δ)] = Φ(-δ) - ∫ φ(|t| S + δ) |t| S Q(a, a S²) du: for a tiny a, Q is at most about a |log(a S²)|, and
346
+ // the integral is a small correction (the integral with P(a, a S²), near Φ(-δ), would carry its error in full)
347
+ const r = integrateCore({ ...pr, t: -pr.t, delta: -pr.delta, kind: "cdfQ" }, needLog);
348
+ const l0 = pnorm(-pr.delta, { logP: true });
349
+ return {
350
+ lin: pnorm(-pr.delta) - r.lin,
351
+ log: needLog ? l0 + Math.log1p(-Math.exp(r.log - l0)) : NaN,
352
+ };
281
353
  }
282
354
  return integrateCore(pr, needLog, pk);
283
355
  }
284
356
  return integrateCore(pr, needLog);
285
357
  }
358
+ /**
359
+ * Below this a, formula B is used at any t: the peak of formula A is not found for a below about 1e-15, and from
360
+ * 1e-5 down its error reaches 5e-15 of P, where formula B, a correction of order a log(t²/a) to Φ(-δ), keeps 1e-16
361
+ */
362
+ const A_TINY = 1e-5;
363
+ /**
364
+ * Above this a (half the degrees of freedom) the integral is taken by Laplace's method where that is accurate (laplace:
365
+ * the far tails from here on, everywhere from about a = 3e8). The width of the density of w is 1/sqrt(a): from about
366
+ * a = 5e7 on the trapezoidal sum loses digits in the far tails (7e-9 of log P at a = 5e7, NaN or Infinity at 1e14), and
367
+ * from 1e29 on it does not resolve the width even near the centre
368
+ */
369
+ const A_LAPLACE = 1e5;
370
+ /**
371
+ * log Φ(u) and its derivatives: [ℓ1, ℓ2, ℓ3, ℓ4] with ℓ1 = m = φ(u)/Φ(u), ℓ2 = -m (u + m), ℓ3 = -ℓ2 (u + m) - m (1 + ℓ2),
372
+ * ℓ4 = -ℓ3 (u + 2m) - 2 ℓ2 (1 + ℓ2). For u = -z < -3, u + m and 1 + ℓ2 cancel (to 1/z and 1/z²); there they come from
373
+ * the continued fraction m - z = K = 1/(z + K2), K2 = 2/(z + 3/(z + 4/(z + ...))) (the continued fraction of Mills'
374
+ * ratio), as u + m = K and 1 + ℓ2 = 1 - (z + K) K = K (K2 - K) (since K (z + K2) = 1). ℓ3 and ℓ4 still cancel, but
375
+ * they only enter the correction term of laplace
376
+ */
377
+ function logPhiDerivs(u) {
378
+ let m;
379
+ let r;
380
+ let p2;
381
+ if (u < -3) {
382
+ const z = -u;
383
+ // (to 1e-16 with these terms: the error falls as e^(-2 z sqrt(n)))
384
+ let k2 = 0;
385
+ for (let n = Math.ceil(20 + 600 / (z * z)); n >= 2; n--)
386
+ k2 = n / (z + k2);
387
+ r = 1 / (z + k2);
388
+ m = z + r;
389
+ p2 = r * (k2 - r);
390
+ }
391
+ else {
392
+ m = millsInv(u);
393
+ r = u + m;
394
+ p2 = 1 - m * r;
395
+ }
396
+ const l2 = -m * r;
397
+ if (u < -1e3) {
398
+ // ℓ3 and ℓ4 from their asymptotic series (the derivatives of ℓ2 = -(1 - 1/z² + 6/z⁴ - 50/z⁶ + ...)): computed as
399
+ // above they keep an error of eps/z², which v⁴ in laplace would turn into an overflow
400
+ const s = 1 / (u * u);
401
+ return [m, l2, -(2 - 24 * s + 300 * s * s) * s / u, (6 - 120 * s + 2100 * s * s) * s * s];
402
+ }
403
+ const l3 = -l2 * r - m * p2;
404
+ const l4 = -l3 * (u + 2 * m) - 2 * l2 * p2;
405
+ return [m, l2, l3, l4];
406
+ }
407
+ /**
408
+ * The integral of integrate (kind "cdf" or "pdf") by Laplace's method in w, for a large a: with L the log of the
409
+ * integrand, w* its maximum and L2 = -L''(w*), L3, L4 the next derivatives there,
410
+ * ∫ e^L dw = e^L(w*) sqrt(2 pi / L2) (1 + L4/(8 L2²) + 5 L3²/(24 L2³) + ...)
411
+ * (the expansion in the moments of a normal variable of variance 1/L2). For the density of w alone (L2 = L3 = L4 = a)
412
+ * the correction is 1/(12a), which cancels stirlerr(a) in C_a. The next terms are of order 1/L2² and q^6 with
413
+ * q = (|v|/2) / (sqrt(L2) max(1, -u)) (v = t S, u = v - δ: the k-th derivative of log Φ(u(w)) is about (v/2)^k ℓk(u),
414
+ * and ℓk(u) about |u|^-k for u << 0); relative to the value they are an error of as much in its log, so they are to be
415
+ * below 1e-17 of |log value| or of 1: near the centre that takes L2 >= 3e8 and q <= 1e-3, far in a tail (log P of -1e6
416
+ * and below) much less. Undefined elsewhere (also where |δ| is of order sqrt(a) with t near δ, where T = (Z + δ)/S is
417
+ * not nearly normal). The derivatives in w follow from v' = v/2:
418
+ * cdf: L = log C_a - a (e^w - 1 - w) + log Φ(u)
419
+ * pdf: L = log C_a - a (e^w - 1 - w) + w/2 - u²/2 - log sqrt(2 pi)
420
+ * The far tails, where w* is far from 0 (e^w* about 2a/t² for |t| >> sqrt(a)), are included: there log Φ(u) is nearly
421
+ * quadratic in v and its derivatives are all of order v², as large as L2.
422
+ */
423
+ function laplace(pr) {
424
+ const { a, t, delta, kind } = pr;
425
+ const cdf = kind === "cdf";
426
+ const at = (w) => {
427
+ const ew = Math.exp(w);
428
+ const v = t * Math.exp(w / 2);
429
+ const u = Math.abs(w) < 1 ? t - delta + t * Math.expm1(w / 2) : v - delta;
430
+ let f;
431
+ if (cdf) {
432
+ const [l1, l2, l3, l4] = logPhiDerivs(u);
433
+ const v2 = v * v;
434
+ // (ℓk falls as |u|^-k where v is huge: multiplied in this order the terms do not overflow)
435
+ f = [
436
+ (l1 * v) / 2,
437
+ (l2 * v2 + l1 * v) / 4,
438
+ (l3 * v * v2 + 3 * l2 * v2 + l1 * v) / 8,
439
+ (l4 * v2 * v2 + 6 * l3 * v * v2 + 7 * l2 * v2 + l1 * v) / 16,
440
+ ];
441
+ }
442
+ else {
443
+ f = [0.5 - (u * v) / 2, -(v * v + u * v) / 4, -(3 * v * v + u * v) / 8, -(7 * v * v + u * v) / 16];
444
+ }
445
+ return { u, v, f, d1: -a * Math.expm1(w) + f[0], L2: a * ew - f[1] };
446
+ };
447
+ // w*: Newton's method on L' inside a bracket (L' > 0 at w = -1400, where v is 0 to the double, and < 0 at 50),
448
+ // bisecting where a step leaves it. Below -1400 e^(w/2) is subnormal
449
+ let lo = -1400;
450
+ let hi = 50;
451
+ let w = 0;
452
+ let p = at(w);
453
+ for (let i = 0; i < 300 && hi - lo > 4e-16 * Math.max(1, Math.abs(w)); i++) {
454
+ // (a Newton step this small leaves an error of L2 step²/2 < 1e-18 in L(w*))
455
+ const step = p.d1 / p.L2;
456
+ if (Math.abs(step) * Math.sqrt(p.L2) < 1e-9)
457
+ break;
458
+ if (p.d1 > 0)
459
+ lo = w;
460
+ else if (p.d1 < 0)
461
+ hi = w;
462
+ else
463
+ break;
464
+ const next = w + step;
465
+ w = next > lo && next < hi ? next : (lo + hi) / 2;
466
+ p = at(w);
467
+ }
468
+ const { u, v, f, L2 } = p;
469
+ const ew = Math.exp(w);
470
+ if (!(w > -1390 && L2 >= 1e5))
471
+ return undefined;
472
+ const r3 = (-a * ew + f[2]) / L2;
473
+ const r4 = (-a * ew + f[3]) / L2;
474
+ const c1 = r4 / L2 / 8 + (5 * r3 * r3) / L2 / 24;
475
+ // log(L2/a), without cancellation near w = 0
476
+ const x = Math.expm1(w) - f[1] / a;
477
+ const lr = Math.abs(x) < 0.5 ? Math.log1p(x) : Math.log(ew - f[1] / a);
478
+ // log C_a + log sqrt(2 pi / L2) + log(1 + c1) - a (e^w - 1 - w); u in double-double where it is formed from t - δ
479
+ const rest = -0.5 * lr - stirlerr(a) + Math.log1p(c1) - a * expm1mxNum(w);
480
+ const ud = Math.abs(w) < 1 ? ddAdd(twoSum(t, -delta), twoProd(t, Math.expm1(w / 2))) : twoSum(v, -delta);
481
+ let value;
482
+ if (cdf) {
483
+ const l = logPhiDD(ud);
484
+ const log = l[0] + (l[1] + rest);
485
+ value = { lin: log < -745 ? 0 : pnorm(ud[0]) * (1 + ud[1] * millsInv(ud[0])) * Math.exp(rest), log };
486
+ }
487
+ else {
488
+ const uu = ddMul(ud, ud);
489
+ const rest2 = rest + w / 2 - LN_SQRT_2PI - uu[1] / 2;
490
+ const hiPart = -uu[0] / 2;
491
+ const log = hiPart + rest2;
492
+ value = { lin: hiPart > -700 ? Math.exp(hiPart) * Math.exp(rest2) : Math.exp(log), log };
493
+ }
494
+ // The neglected terms (in the far tails, where only the log is representable, a smaller L2 is enough)
495
+ const q = cdf ? Math.abs(v) / 2 / (Math.sqrt(L2) * Math.max(1, -u)) : 0;
496
+ return 1 / (L2 * L2) + q ** 6 <= 1e-17 * Math.max(1, Math.abs(value.log)) ? value : undefined;
497
+ }
286
498
  function logAddExp(x, y) {
287
499
  if (x === -Infinity)
288
500
  return y;
@@ -338,45 +550,68 @@ function farLimit(a, delta) {
338
550
  }
339
551
  /** Log of the far tail (upper if t > 0, lower if t < 0). Extrapolated if |t| > farLimit */
340
552
  function farTailLog(t, a, delta) {
553
+ return Math.abs(t) > farLimit(a, delta) ? farTails(t, a, delta, t < 0).log : pntBoth(t, 2 * a, delta, t < 0).log;
554
+ }
555
+ /**
556
+ * P[T <= t] (lower) / P[T > t] for |t| > T0 = farLimit, from both tails at T0 (same sign): the far tail times
557
+ * (T0/|t|)^(2a), and the near tail grown by what the far tail lost. The near tail is 1 - (far) unless the far tail
558
+ * is still the larger (for a tiny a it falls only as |t|^(-2a), from about Φ(±δ))
559
+ */
560
+ function farTails(t, a, delta, lower) {
341
561
  const T0 = farLimit(a, delta);
342
562
  const s = Math.sign(t);
343
- const at = Math.min(Math.abs(t), T0);
344
- const pr = s > 0 ? problem(a, -at, -delta, "cdf") : problem(a, -at, delta, "cdf");
345
- const l0 = integrate(pr, true).log;
346
- return Math.abs(t) > T0 ? l0 + 2 * a * (Math.log(T0) - Math.log(Math.abs(t))) : l0;
563
+ const farLower = s < 0;
564
+ const f0 = pntBoth(s * T0, 2 * a, delta, farLower);
565
+ const r = Math.log(Math.abs(t)) - Math.log(T0);
566
+ const k = 2 * a * r;
567
+ const far = { lin: f0.lin > 0 ? f0.lin * Math.exp(-k) : Math.exp(f0.log - k), log: f0.log - k };
568
+ if (lower === farLower)
569
+ return far;
570
+ if (far.lin < 0.5)
571
+ return { lin: 1 - far.lin, log: Math.log1p(-far.lin) };
572
+ const n0 = pntBoth(s * T0, 2 * a, delta, !farLower);
573
+ const gain = -Math.expm1(-k);
574
+ // (log k from log 2a where k is so small that it may be subnormal: for a subnormal a it kept a few bits only)
575
+ const logGain = k < 1e-10 ? Math.log(2 * a) + Math.log(r) - k / 2 : Math.log(gain);
576
+ return { lin: n0.lin + f0.lin * gain, log: logAddExp(n0.log, f0.log + logGain) };
577
+ }
578
+ /**
579
+ * Whether |t| is so small that P[T <= t] = Φ(-δ) and P[T > t] = Φ(δ), their values at t = 0, to double precision.
580
+ * For t > 0, P[T <= t] - Φ(-δ) = P[0 < Z + δ <= t S] = ∫ φ(x - δ) Q(a, a x²/t²) dx over x > 0 (t < 0 likewise). Beyond
581
+ * x1 = |t| sqrt(y1/a), y1 = 4a + 2δ² + 800, Q(a, y) < e^(-0.4 y) is far below Φ(∓δ); below x1 the integral is at most
582
+ * x1 φ(δ) (x1 |δ| < 1), at most x1 (|δ| + 2) relative to Φ(∓δ). Formula B would otherwise need S out to |δ|/|t|, where
583
+ * e^w overflows
584
+ */
585
+ function nearZero(t, a, delta) {
586
+ // (|t|/sqrt(a) first, and sqrt(y1) as a hypot: y1/a overflowed for a below about 1e-300 with a large δ, and at t = 0
587
+ // the test was NaN, false, so that the integral was taken at t = 0 and gave NaN to qt)
588
+ return (Math.abs(t) / Math.sqrt(a)) * Math.hypot(Math.SQRT2 * delta, Math.sqrt(4 * a + 800)) * (Math.abs(delta) + 2) <= 1e-17;
347
589
  }
348
- /** Linear value and log of P[T <= t] (lower) / P[T > t] (the log of a value near 1 is built from the other side only when needed) */
349
- function pntBoth(t, df, delta, lower) {
590
+ /** Linear value and log of P[T <= t] (lower) / P[T > t] (the log may be NaN unless needLog) */
591
+ function pntBoth(t, df, delta, lower, needLog = true) {
350
592
  const a = df / 2;
351
- if (Math.abs(t) > farLimit(a, delta)) {
352
- const lf = farTailLog(t, a, delta);
353
- const far = t > 0 ? !lower : lower;
354
- if (far)
355
- return { lin: Math.exp(lf), log: lf };
356
- return { lin: -Math.expm1(lf), log: Math.log1p(-Math.exp(lf)) };
593
+ if (nearZero(t, a, delta)) {
594
+ const d = lower ? -delta : delta;
595
+ return { lin: pnorm(d), log: pnorm(d, { logP: true }) };
357
596
  }
358
- // The upper tail E[Φ(δ - t S)] is the lower tail with (t, δ) replaced by (-t, -δ)
359
- const own = integrate(lower ? problem(a, t, delta, "cdf") : problem(a, -t, -delta, "cdf"), true);
360
- if (own.lin <= 0.5)
361
- return own;
362
- let lg;
363
- return {
364
- lin: own.lin,
365
- get log() {
366
- // The log of a value near 1 is built with log1p from the small value of the other side
367
- lg ??= Math.log1p(-integrate(lower ? problem(a, -t, -delta, "cdf") : problem(a, t, delta, "cdf"), false).lin);
368
- return lg;
369
- },
370
- };
597
+ if (Math.abs(t) > farLimit(a, delta))
598
+ return farTails(t, a, delta, lower);
599
+ // The upper tail E[Φ(δ - t S)] is the lower tail with (t, δ) replaced by (-t, -δ). The smaller tail is integrated
600
+ // and the larger is 1 - (smaller), with its log by log1p: integrated itself it can exceed 1 by a few ulps. The lower
601
+ // tail is likely the smaller below the median, about δ (when the guess is wrong the other tail is integrated too)
602
+ const tail = (l) => integrate(l ? problem(a, t, delta, "cdf") : problem(a, -t, -delta, "cdf"), needLog && l === lower);
603
+ let side = t < delta;
604
+ let v = tail(side);
605
+ if (v.lin > 0.5) {
606
+ side = !side;
607
+ v = tail(side);
608
+ }
609
+ if (side === lower)
610
+ return v;
611
+ return { lin: 1 - v.lin, log: Math.log1p(-v.lin) };
371
612
  }
372
613
  function pntRaw(t, df, delta, lower, log) {
373
- if (!log) {
374
- const a = df / 2;
375
- if (Math.abs(t) <= farLimit(a, delta)) {
376
- return integrate(lower ? problem(a, t, delta, "cdf") : problem(a, -t, -delta, "cdf"), false).lin;
377
- }
378
- }
379
- const v = pntBoth(t, df, delta, lower);
614
+ const v = pntBoth(t, df, delta, lower, log);
380
615
  return log ? v.log : v.lin;
381
616
  }
382
617
  function dntRaw(x, df, delta, log) {
@@ -391,11 +626,71 @@ function dntRaw(x, df, delta, log) {
391
626
  const v = integrate(problem(a, x, delta, "pdf"), log);
392
627
  return log ? v.log : v.lin;
393
628
  }
394
- export function dnt1(x, df, ncp, log) {
395
- if (Number.isNaN(x) || Number.isNaN(df) || Number.isNaN(ncp))
629
+ /**
630
+ * Above this df the central and noncentral t are taken from their limits (hugeDf*; shared with t.ts). The t
631
+ * differs from the normal by terms of relative order t²/ν and 1/ν: where y = t²/ν < 1e-17 it is the normal to the
632
+ * double (the absolute error in the log, about t⁴/ν, is below 1e-180 wherever the linear value is above the
633
+ * underflow), and beyond, |t| > 3e91, the log of the far tail and of the density is -(ν/2) log1p(y) up to terms
634
+ * below 1e-179 of it. The general code fails from about 1.3e300 on (NaN where its intermediate terms overflow)
635
+ */
636
+ export const HUGE_DF = 1e200;
637
+ /** y = t²/ν (t² may overflow on its own) */
638
+ export function hugeDfRatio(t, n) {
639
+ const u = t / Math.sqrt(n);
640
+ return u * u;
641
+ }
642
+ /**
643
+ * Log of the far tail beyond |t| and of the density at t (relative error about eps) for n > HUGE_DF and
644
+ * hugeDfRatio(t, n) >= 1e-17: -(n/2) log1p(t²/n), formed without overflow
645
+ */
646
+ export function hugeDfTailLog(t, n) {
647
+ const u = Math.abs(t) / Math.sqrt(n);
648
+ // log1p(u²) = 2 log u + log1p(1/u²) where u² is huge (n log u may overflow: the log is then -Infinity, as it is)
649
+ if (u > 1e8)
650
+ return -n * (Math.log(u) + 0.5 * Math.log1p(1 / (u * u)));
651
+ const y = u * u;
652
+ // (n/2) log1p(y) = (t²/2) log1p(y)/y, the ratio by its series for a small y (error y⁴/5)
653
+ const g = y < 1e-5 ? 1 - y * (1 / 2 - y * (1 / 3 - y / 4)) : Math.log1p(y) / y;
654
+ return -0.5 * Math.abs(t) * (Math.abs(t) * g);
655
+ }
656
+ /**
657
+ * |t| with hugeDfTailLog(t, n) = logTarget (logTarget < 0), Infinity beyond the largest double: t² = n expm1(-2 logTarget / n).
658
+ * (sqrt(n) is taken apart: through exp(log t) its log, up to 354, would multiply the rounding error)
659
+ */
660
+ export function hugeDfTailQuantile(logTarget, n) {
661
+ const r = 2 * (-logTarget / n);
662
+ return r < 700 ? Math.sqrt(n) * Math.sqrt(Math.expm1(r)) : Math.sqrt(n) * Math.exp(r / 2);
663
+ }
664
+ /**
665
+ * P[T <= t] (lower) / P[T > t] for n > HUGE_DF and hugeDfRatio(t, n) >= 1e-17 from hugeDfTailLog: the tail beyond |t|
666
+ * is its exp (0), the other is 1
667
+ */
668
+ export function hugeDfTail(t, n, lowerTail, logP) {
669
+ const l = hugeDfTailLog(t, n);
670
+ if (t < 0 === lowerTail)
671
+ return logP ? l : Math.exp(l);
672
+ return logP ? Math.log1p(-Math.exp(l)) : 1 - Math.exp(l);
673
+ }
674
+ /**
675
+ * Whether the noncentral t at n > HUGE_DF and hugeDfRatio(t, n) >= 1e-17 has the central far tail and density
676
+ * (hugeDfTailLog): δ shifts their log by about δ min(|t|, sqrt(n)), below 1e-19 of it here
677
+ */
678
+ function hugeDfCentral(t, n, delta) {
679
+ return Math.abs(delta) <= 1e-20 * Math.min(Math.abs(t), Math.sqrt(n));
680
+ }
681
+ /**
682
+ * df with a nonzero half: the smallest subnormal, whose half rounds to 0, is taken as twice itself (a = 5e-324). Below
683
+ * about 1e-308 a = df/2 is rounded to the subnormal grid anyway; only the terms of order a beside Φ(∓δ) feel that
684
+ */
685
+ function halvable(df) {
686
+ return df === Number.MIN_VALUE ? 2 * df : df;
687
+ }
688
+ export function dnt1(x, df0, ncp, log) {
689
+ if (Number.isNaN(x) || Number.isNaN(df0) || Number.isNaN(ncp))
396
690
  return NaN;
397
- if (df <= 0)
691
+ if (df0 <= 0)
398
692
  return NaN;
693
+ const df = halvable(df0);
399
694
  if (!Number.isFinite(x) || !Number.isFinite(ncp))
400
695
  return log ? -Infinity : 0;
401
696
  if (df === Infinity) {
@@ -403,13 +698,22 @@ export function dnt1(x, df, ncp, log) {
403
698
  const lv = -0.5 * z * z - LN_SQRT_2PI;
404
699
  return log ? lv : Math.exp(lv);
405
700
  }
701
+ if (df > HUGE_DF) {
702
+ if (hugeDfRatio(x, df) < 1e-17)
703
+ return dnorm(x - ncp, { log });
704
+ if (hugeDfCentral(x, df, ncp)) {
705
+ const lv = hugeDfTailLog(x, df);
706
+ return log ? lv : Math.exp(lv);
707
+ }
708
+ }
406
709
  return dntRaw(x, df, ncp, log);
407
710
  }
408
- export function pnt1(q, df, ncp, lowerTail, logP) {
409
- if (Number.isNaN(q) || Number.isNaN(df) || Number.isNaN(ncp))
711
+ export function pnt1(q, df0, ncp, lowerTail, logP) {
712
+ if (Number.isNaN(q) || Number.isNaN(df0) || Number.isNaN(ncp))
410
713
  return NaN;
411
- if (df <= 0)
714
+ if (df0 <= 0)
412
715
  return NaN;
716
+ const df = halvable(df0);
413
717
  const zero = lowerTail ? (logP ? -Infinity : 0) : logP ? 0 : 1;
414
718
  const one = lowerTail ? (logP ? 0 : 1) : logP ? -Infinity : 0;
415
719
  if (q === Infinity)
@@ -425,13 +729,22 @@ export function pnt1(q, df, ncp, lowerTail, logP) {
425
729
  return pnorm(q - ncp, { lowerTail, logP });
426
730
  if (q === 0)
427
731
  return pnorm(-ncp, { lowerTail, logP });
732
+ if (df > HUGE_DF) {
733
+ if (hugeDfRatio(q, df) < 1e-17)
734
+ return pnorm(q - ncp, { lowerTail, logP });
735
+ // The far tail beyond |q| (R 4.5.2 gives 0.5 for pt(-4.05e269, 3.586e307, ncp = 1), far in the left tail of
736
+ // what is N(1, 1) to the double; the lower tail is 0 here)
737
+ if (hugeDfCentral(q, df, ncp))
738
+ return hugeDfTail(q, df, lowerTail, logP);
739
+ }
428
740
  return pntRaw(q, df, ncp, lowerTail, logP);
429
741
  }
430
- export function qnt1(p, df, ncp, lowerTail, logP) {
431
- if (Number.isNaN(p) || Number.isNaN(df) || Number.isNaN(ncp))
742
+ export function qnt1(p, df0, ncp, lowerTail, logP) {
743
+ if (Number.isNaN(p) || Number.isNaN(df0) || Number.isNaN(ncp))
432
744
  return NaN;
433
- if (df <= 0)
745
+ if (df0 <= 0)
434
746
  return NaN;
747
+ const df = halvable(df0);
435
748
  const b = quantileBoundaries(p, -Infinity, Infinity, lowerTail, logP);
436
749
  if (b !== undefined)
437
750
  return b;
@@ -441,6 +754,15 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
441
754
  if (!Number.isFinite(ncp))
442
755
  return NaN;
443
756
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
757
+ if (df > HUGE_DF) {
758
+ // The quantiles of the limits of pnt1
759
+ const x = ncp + qnorm(p, { lowerTail, logP });
760
+ if (hugeDfRatio(x, df) < 1e-17)
761
+ return x;
762
+ const y = hugeDfTailQuantile(logTarget, df);
763
+ if (hugeDfCentral(y, df, ncp))
764
+ return lower ? -y : y;
765
+ }
444
766
  // Starting value: normal approximation (mean δ; t spreads a little in the direction of δ)
445
767
  const z = qnorm(logTarget, { lowerTail: lower, logP: true });
446
768
  const x0 = ncp + z * Math.sqrt(1 + (ncp * ncp) / (2 * df));
@@ -475,6 +797,22 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
475
797
  }
476
798
  hi = T0;
477
799
  }
800
+ else if (df < 1e-3 && cdfY(Number.MAX_VALUE, true, true) < logTarget) {
801
+ // The near tail grows only as 1 - c |t|^(-2a) (c about Φ(±δ)), so for a small a it can stay below the target up to
802
+ // the largest double (that needs 2a log(1.8e308) < log(2c), a < 5e-4): the quantile is beyond it
803
+ return s * Infinity;
804
+ }
805
+ // Where the normal start falls on the other side of 0 (a small ν with a large δ, for one): on the side of δ,
806
+ // P[sT <= y] = P[s Z + |δ| <= y S] is about P[S >= |δ|/y] = Q(a, a δ²/y²) when Φ is a step on the scale of S, so y
807
+ // from the gamma quantile. (The start was 1, far above the quantile, from where the first step went to y = 0 and
808
+ // the solver bisected back in log y across the doubly exponential fall of P: 50 ms at df = 1e-200, ncp = 1e4)
809
+ const sideStart = () => {
810
+ if (s * ncp <= 0)
811
+ return 1;
812
+ const g = qgammaStd(logTarget, df / 2, !lowerY, true);
813
+ const y0 = Math.abs(ncp) * Math.sqrt(df / 2 / g);
814
+ return y0 > 0 && Number.isFinite(y0) ? y0 : 1;
815
+ };
478
816
  const y = invertContinuous({
479
817
  logTarget,
480
818
  ...(linearTarget !== undefined && { linearTarget }),
@@ -482,7 +820,7 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
482
820
  cdf: (y, l) => cdfY(y, l, false),
483
821
  cdfLog: (y, l) => cdfY(y, l, true),
484
822
  pdfLog: (y) => dntRaw(s * y, df, ncp, true),
485
- x0: Math.min(Math.abs(x0) > 0 && Number.isFinite(x0) && Math.sign(x0) === s ? Math.abs(x0) : 1, hi / 2),
823
+ x0: Math.min(Math.abs(x0) > 0 && Number.isFinite(x0) && Math.sign(x0) === s ? Math.abs(x0) : sideStart(), hi / 2),
486
824
  lo: 0,
487
825
  hi,
488
826
  positive: true,