@numero-uno-jpn/rstats 0.15.1 → 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 (80) hide show
  1. package/CHANGELOG.md +33 -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-3QTVXDUM.js → chunk-3WQCKGKP.js} +2 -2
  6. package/dist/chunks/{chunk-4ILI2FSB.js → chunk-4Z2XDWKV.js} +1 -1
  7. package/dist/chunks/{chunk-5XQZNKHZ.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-5OSQ76OO.js → chunk-HBMHR5SS.js} +2 -2
  11. package/dist/chunks/{chunk-7J4HW6VF.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-735NNFAS.js → chunk-PEYGUK32.js} +2 -2
  15. package/dist/chunks/{chunk-H4CHJMFU.js → chunk-PWVQVJTP.js} +1 -1
  16. package/dist/chunks/{chunk-LY2T6DA6.js → chunk-Q4PGYESP.js} +2 -2
  17. package/dist/chunks/{chunk-OLPTFKIZ.js → chunk-RCAL4VHM.js} +2 -2
  18. package/dist/chunks/{chunk-IQOVOHZG.js → chunk-SREPSVTT.js} +2 -2
  19. package/dist/chunks/chunk-UFT662QZ.js +2 -0
  20. package/dist/chunks/{chunk-Z3C3G5XI.js → chunk-VWJ74UHC.js} +2 -2
  21. package/dist/chunks/{chunk-SAZAEPZC.js → chunk-XNPU54NH.js} +1 -1
  22. package/dist/chunks/{chunk-5SQFDLNG.js → chunk-XPLDEK6D.js} +2 -2
  23. package/dist/chunks/{chunk-VOIJKNL2.js → chunk-YGT4P7EU.js} +1 -1
  24. package/dist/chunks/{chunk-GEJCBCMP.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 +330 -92
  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/t.js +48 -10
  45. package/dist/distributions/triangular.js +66 -27
  46. package/dist/distributions/tukey.js +94 -50
  47. package/dist/distributions/uniform.js +12 -9
  48. package/dist/distributions/weibull.js +43 -8
  49. package/dist/distributions.js +2 -2
  50. package/dist/internal/ddexp.d.ts +5 -0
  51. package/dist/internal/ddexp.js +28 -3
  52. package/dist/internal/discrete.js +30 -7
  53. package/dist/internal/invert.js +49 -0
  54. package/dist/internal/noncentral.d.ts +34 -0
  55. package/dist/internal/noncentral.js +115 -2
  56. package/dist/internal/poissonMixture.d.ts +7 -2
  57. package/dist/internal/poissonMixture.js +113 -32
  58. package/dist/linalg.js +2 -2
  59. package/dist/mixed.js +2 -2
  60. package/dist/numerics.js +2 -2
  61. package/dist/rstats.js +14 -14
  62. package/dist/special/dd.d.ts +1 -1
  63. package/dist/special/dd.js +4 -1
  64. package/dist/special/igam.js +93 -15
  65. package/dist/special/incbet.d.ts +10 -0
  66. package/dist/special/incbet.js +154 -48
  67. package/dist/special/incbetLargeA.js +47 -13
  68. package/dist/special/incbetPrefactor.d.ts +52 -0
  69. package/dist/special/incbetPrefactor.js +92 -0
  70. package/dist/special/incbetTemme.js +15 -3
  71. package/dist/special/loader.js +33 -7
  72. package/dist/special.js +2 -2
  73. package/dist/tests.js +2 -2
  74. package/package.json +1 -1
  75. package/dist/chunks/chunk-5YMP4WAJ.js +0 -2
  76. package/dist/chunks/chunk-BDJPSEA7.js +0 -2
  77. package/dist/chunks/chunk-KO6QQPC6.js +0 -2
  78. package/dist/chunks/chunk-TYFGVCVQ.js +0 -2
  79. package/dist/chunks/chunk-UWBYDIOH.js +0 -2
  80. package/dist/chunks/chunk-UZHY5DWN.js +0 -2
@@ -16,7 +16,7 @@ export declare function ddMulNum(a: DD, b: number): DD;
16
16
  export declare function ddDiv(a: DD, b: DD): DD;
17
17
  export declare function ddDivNum(a: DD, b: number): DD;
18
18
  /**
19
- * Natural log in double-double. x > 0 and finite.
19
+ * Natural log in double-double. 0 gives -Infinity, Infinity gives Infinity, a negative x or NaN gives NaN.
20
20
  *
21
21
  * After reducing x = m 2^k (m ∈ [1/√2, √2)), divide m by the nearest c = i/128 and use
22
22
  * log m = log c + 2 atanh(s), s = (m - c)/(m + c) (|s| <= 0.0028)
@@ -373,7 +373,7 @@ const LOGTAB128 = [
373
373
  [0.3574558889218038, -2.5136910072413547e-17],
374
374
  ];
375
375
  /**
376
- * Natural log in double-double. x > 0 and finite.
376
+ * Natural log in double-double. 0 gives -Infinity, Infinity gives Infinity, a negative x or NaN gives NaN.
377
377
  *
378
378
  * After reducing x = m 2^k (m ∈ [1/√2, √2)), divide m by the nearest c = i/128 and use
379
379
  * log m = log c + 2 atanh(s), s = (m - c)/(m + c) (|s| <= 0.0028)
@@ -386,6 +386,9 @@ const LOGTAB128 = [
386
386
  export function ddLog(x) {
387
387
  if (!ddEnabled)
388
388
  return [Math.log(x[0]), 0];
389
+ // Outside (0, Infinity) the table index below is out of range; answer as Math.log does
390
+ if (!(x[0] > 0 && x[0] < Infinity))
391
+ return [Math.log(x[0]), 0];
389
392
  // x = m 2^k, m ∈ [1/√2, √2). Subnormals are first multiplied by 2^600 to make them normal (exact, being a power of 2)
390
393
  let x0 = x[0];
391
394
  let x1 = x[1];
@@ -8,12 +8,12 @@
8
8
  // series or continued fraction, never by taking the log of a value that over/underflowed in exp
9
9
  // - The prefactor x^a e^-x / Gamma(a) is computed with Loader's dpoisRaw (= x^a e^-x / Gamma(a+1)),
10
10
  // to avoid cancellation in the log for large a and x
11
- import { erfc } from "./erf.js";
11
+ import { erfc, erfcxNonNegative } from "./erf.js";
12
12
  import { SPLITTER } from "./dd.js";
13
13
  import { MACHEP } from "./constants.js";
14
14
  import { lgamma, lgamma1p } from "./gamma.js";
15
15
  import { IGAM_ASYMP_COEFF_D, IGAM_ASYMP_COEFF_K, IGAM_ASYMP_COEFF_N } from "./igamAsympCoeff.js";
16
- import { dpoisRaw, dpoisRawBoth } from "./loader.js";
16
+ import { bd0dd, dpoisRaw, dpoisRawBoth } from "./loader.js";
17
17
  import { log1pmx } from "./log1pmx.js";
18
18
  // xsf uses 2000. For a around 1e6 with x close to a, the series and continued fraction take thousands of iterations, so raise it
19
19
  const MAXITER = 10_000_000;
@@ -117,6 +117,8 @@ function igamcContinuedFractionBoth(a, x) {
117
117
  }
118
118
  /** The continued fraction of DLMF 8.9.2: Q(a, x) = x^a e^-x / Gamma(a) times this */
119
119
  export function igamcContinuedFractionValue(a, x) {
120
+ if (x > 1e20)
121
+ return igamcContinuedFractionLentz(a, x);
120
122
  let y = 1 - a;
121
123
  let z = x + y + 1;
122
124
  let c = 0;
@@ -156,6 +158,35 @@ export function igamcContinuedFractionValue(a, x) {
156
158
  }
157
159
  return ans;
158
160
  }
161
+ /**
162
+ * The same continued fraction by the modified Lentz method (only ratios are kept, so nothing grows). For large x
163
+ * the convergents above overflow: the first denominator is already (x + 2 - a) x, and each step multiplies by about x
164
+ * while the rescaling divides by only 2^52 (pgamma(7.2e60, 6.1e55), ppois(3.66e124, 8.1e125) and ppois(3.4e240,
165
+ * 5.5e241) were NaN). Used above 1e20, where overflow takes about 70 steps or fewer
166
+ */
167
+ function igamcContinuedFractionLentz(a, x) {
168
+ const tiny = 1e-300;
169
+ let b = x + 1 - a;
170
+ let c = 1 / tiny;
171
+ let d = 1 / b;
172
+ let h = d;
173
+ for (let i = 1; i < MAXITER; i++) {
174
+ const an = -i * (i - a);
175
+ b += 2;
176
+ d = an * d + b;
177
+ if (Math.abs(d) < tiny)
178
+ d = tiny;
179
+ c = b + an / c;
180
+ if (Math.abs(c) < tiny)
181
+ c = tiny;
182
+ d = 1 / d;
183
+ const del = d * c;
184
+ h *= del;
185
+ if (Math.abs(del - 1) <= MACHEP)
186
+ break;
187
+ }
188
+ return h;
189
+ }
159
190
  /** Q(a, x) by DLMF 8.7.3. For small x (the value does not approach 0) */
160
191
  function igamcSeries(a, x) {
161
192
  let fac = 1;
@@ -177,16 +208,23 @@ function igamcSeries(a, x) {
177
208
  /** Temme's uniform asymptotic expansion for a close to x (DLMF 8.12.3/8.12.4) */
178
209
  function asymptoticSeries(a, x, lower) {
179
210
  const sgn = lower ? -1 : 1;
211
+ const eta = temmeEta(a, x);
212
+ let res = 0.5 * erfc(sgn * eta * Math.sqrt(a / 2));
213
+ res += (sgn * Math.exp(-0.5 * a * eta * eta) * temmeSum(a, eta)) / Math.sqrt(2 * Math.PI * a);
214
+ return res;
215
+ }
216
+ /** η of Temme's expansion: η^2 / 2 = λ - 1 - log λ (λ = x / a), with the sign of λ - 1 */
217
+ function temmeEta(a, x) {
180
218
  const lambda = x / a;
181
219
  const sigma = (x - a) / a;
182
- let eta;
183
220
  if (lambda > 1)
184
- eta = Math.sqrt(-2 * log1pmx(sigma));
185
- else if (lambda < 1)
186
- eta = -Math.sqrt(-2 * log1pmx(sigma));
187
- else
188
- eta = 0;
189
- let res = 0.5 * erfc(sgn * eta * Math.sqrt(a / 2));
221
+ return Math.sqrt(-2 * log1pmx(sigma));
222
+ if (lambda < 1)
223
+ return -Math.sqrt(-2 * log1pmx(sigma));
224
+ return 0;
225
+ }
226
+ /** Σ_k c_k(η) a^-k of Temme's expansion */
227
+ function temmeSum(a, eta) {
190
228
  const etapow = new Array(IGAM_ASYMP_COEFF_N).fill(0);
191
229
  etapow[0] = 1;
192
230
  let maxpow = 0;
@@ -216,8 +254,46 @@ function asymptoticSeries(a, x, lower) {
216
254
  absoldterm = absterm;
217
255
  afac /= a;
218
256
  }
219
- res += (sgn * Math.exp(-0.5 * a * eta * eta) * sum) / Math.sqrt(2 * Math.PI * a);
220
- return res;
257
+ return sum;
258
+ }
259
+ /** xsf's region for Temme's expansion: |x - a| / a below 0.3 for 20 < a < 200, within 4.5 standard deviations for larger a */
260
+ function xsfAsymptotic(a, absxmaA) {
261
+ return (a > SMALL && a < LARGE && absxmaA < SMALLRATIO) || (a > LARGE && absxmaA < LARGERATIO / Math.sqrt(a));
262
+ }
263
+ /**
264
+ * Above this a, Temme's expansion is used at every x (below 1e15 a): the double-double series of P overflows in its
265
+ * products of terms around a (pgamma(0.99 * 2^1000, 2^1000) was NaN after 0.1 s), and only the leading term of the
266
+ * expansion is left
267
+ */
268
+ const HUGE_A = 1e299;
269
+ /**
270
+ * Beyond xsf's region, Temme's expansion is also used for a > 200 with |x - a| / a below 1e-3. There the series and
271
+ * the continued fraction need about 40 a / |x - a| terms (beyond 10^7 for a above 1e14: ppois(3.28e19 + 1e11, 3.28e19)
272
+ * took 0.15 s per call and stopped short of convergence), while η is below 1e-3 and the expansion converges in a few
273
+ * terms; and at every x above HUGE_A. See temmeTail for the form used.
274
+ */
275
+ const farAsymptotic = (a, absxmaA) => a > LARGE && (absxmaA < 1e-3 || a > HUGE_A);
276
+ /**
277
+ * [log, linear] of the smaller tail (the upper if x > a) by Temme's expansion, in the form
278
+ * e^(-a η^2 / 2) (erfcx(y) / 2 ± S / sqrt(2π a)), y = |η| sqrt(a / 2),
279
+ * with a η^2 / 2 = a log(a / x) + x - a computed as Loader's bd0 in double-double. Forming erfc(y) and
280
+ * e^(-a η^2 / 2) from η directly carries the rounding of η times a η^2 (1e-14 relative at 11 standard deviations)
281
+ */
282
+ function temmeTail(a, x) {
283
+ const e = bd0dd(a, [x, 0]);
284
+ const sgn = x > a ? 1 : -1;
285
+ const eta = temmeEta(a, x);
286
+ // Beyond a = 1e299 the sum is c_0(η) alone (the next term is c_1 / a), used for any x there (see farAsymptotic):
287
+ // in closed form c_0 = 1/(λ - 1) - 1/η away from η = 0, where the power series in η no longer converges
288
+ const s = a > HUGE_A && Math.abs(eta) > 0.1 ? 1 / ((x - a) / a) - 1 / eta : temmeSum(a, eta);
289
+ const b = 0.5 * erfcxNonNegative(Math.sqrt(e[0] + e[1])) + (sgn * s) / Math.sqrt(2 * Math.PI * a);
290
+ // (far below the subnormals e[1], half an ulp of E, can exceed 1)
291
+ return [-e[0] - e[1] + Math.log(b), e[0] > 2000 ? 0 : Math.exp(-e[0]) * (1 - e[1]) * b];
292
+ }
293
+ /** [log, linear] of P(a, x) (Q if !lower) in the region of farAsymptotic */
294
+ function farTail(a, x, lower) {
295
+ const [log, lin] = temmeTail(a, x);
296
+ return (x > a) !== lower ? [log, lin] : [Math.log1p(-lin), 1 - lin];
221
297
  }
222
298
  /**
223
299
  * Decide which tail to compute directly and return its value. Same case split as xsf's igamc.
@@ -280,11 +356,12 @@ export function gammaIncBoth(a, x, lower) {
280
356
  return [lq, Math.exp(lq)];
281
357
  }
282
358
  const absxmaA = Math.abs(x - a) / a;
283
- if ((a > SMALL && a < LARGE && absxmaA < SMALLRATIO) ||
284
- (a > LARGE && absxmaA < LARGERATIO / Math.sqrt(a))) {
359
+ if (xsfAsymptotic(a, absxmaA)) {
285
360
  const v = asymptoticSeries(a, x, lower);
286
361
  return [v > 0.5 ? Math.log1p(-asymptoticSeries(a, x, !lower)) : Math.log(v), v];
287
362
  }
363
+ if (farAsymptotic(a, absxmaA))
364
+ return farTail(a, x, lower);
288
365
  const d = directTailBoth(a, x);
289
366
  if (d.lower === lower)
290
367
  return [d.log, d.lin];
@@ -325,14 +402,15 @@ export function gammaInc(a, x, lower, log) {
325
402
  }
326
403
  /* Asymptotic regime where a ~ x: both tails can be computed directly */
327
404
  const absxmaA = Math.abs(x - a) / a;
328
- if ((a > SMALL && a < LARGE && absxmaA < SMALLRATIO) ||
329
- (a > LARGE && absxmaA < LARGERATIO / Math.sqrt(a))) {
405
+ if (xsfAsymptotic(a, absxmaA)) {
330
406
  const v = asymptoticSeries(a, x, lower);
331
407
  if (!log)
332
408
  return v;
333
409
  // The log of a value near 1 is built with log1p from the small value of the other side
334
410
  return v > 0.5 ? Math.log1p(-asymptoticSeries(a, x, !lower)) : Math.log(v);
335
411
  }
412
+ if (farAsymptotic(a, absxmaA))
413
+ return farTail(a, x, lower)[log ? 0 : 1];
336
414
  if (log) {
337
415
  const d = directTail(a, x, true);
338
416
  if (d.lower === lower)
@@ -23,3 +23,13 @@ export declare function betaIncDD(a: number, b: number, xd: DD, xcd: DD, lower:
23
23
  export declare function betaIncBothDD(a: number, b: number, xd: DD, xcd: DD, lower: boolean): [number, number];
24
24
  /** Version of betaInc returning both (takes x and 1 - x in double precision, like betaInc) */
25
25
  export declare function betaIncBoth(a: number, b: number, x: number, xc: number, lower: boolean): [number, number];
26
+ /**
27
+ * I_x(a, b) (lower) or 1 - I_x(a, b) for x below DBL_MIN, from x and lx = log x in double-double (x itself may have
28
+ * underflowed to 0, as in the F distribution far out: only lx then carries it), as [log, linear] (log NaN unless
29
+ * wantLog). From the series I_x(a, b) = x^a / (a B(a, b)) (1 + a S), S = pseriesSum(a, b, x): the terms of S are about
30
+ * (-b x)^n / n!, and b x is at most 4 here (b near the largest double), mostly negligible.
31
+ * log(1/(a B(a, b))) is lgamma(a+b) - lgamma(b) - lgamma(a+1) without subtraction, or for a small shape
32
+ * log(b/(a + b)) + log Γ(1+a+b)/(Γ(1+a) Γ(1+b)) with the ratio r = b/(a + b) kept on the linear scale (as a log, its
33
+ * rounding of ε |log r| would become the relative error of the result)
34
+ */
35
+ export declare function betaIncTinyX(a: number, b: number, x: number, lx: DD, lower: boolean, wantLog: boolean): [number, number];
@@ -9,13 +9,15 @@
9
9
  // - For each tail, choose the frame in which it can be computed directly (I_x(a,b) or I_{1-x}(b,a)),
10
10
  // because forming it as 1 - (the other) loses digits in the smaller tail
11
11
  // - The factor x^a (1-x)^b / B(a, b) in front of the series and continued fractions is computed with
12
- // Loader's dbinomRaw (avoids cancellation in the log for large a, b)
12
+ // Loader's dbinomRaw (avoids cancellation in the log for large a, b), or for a small shape, or a huge one with the
13
+ // other moderate, from the forms of incbetPrefactor.ts
13
14
  // - The log is formed directly from the result of each computation
14
15
  import { MACHEP } from "./constants.js";
15
16
  import { dbinomExponent, dbinomRawDD } from "./loader.js";
16
17
  import { ddAdd, ddDiv, ddLog, ddMul, ddMulNum, ddSub, isDoubleDouble, SPLITTER, twoProd, twoSum } from "./dd.js";
17
18
  import { lgamma1p } from "./gamma.js";
18
- import { lgammaDiff } from "./lgammaDiff.js";
19
+ import { lgammaDiffDD } from "./lgammaDiff.js";
20
+ import { HUGE_SHAPE, HUGE_SHAPE_MAX_SMALL, lgammaRatioHuge, prefactorParts, SMALL_SHAPE, smallShapeG, } from "./incbetPrefactor.js";
19
21
  import { betaIncTemme, TEMME_MIN_M } from "./incbetTemme.js";
20
22
  import { betaIncLargeA, LARGE_A_MIN, SMALL_B_MAX } from "./incbetLargeA.js";
21
23
  const BIG = 4.503599627370496e15;
@@ -24,13 +26,20 @@ const BIGINV = 2.22044604925031308085e-16;
24
26
  * Log of x^a (1-x)^b / B(a, b).
25
27
  * Since dbinom(a; a + b, x) = Gamma(a+b+1)/(Gamma(a+1) Gamma(b+1)) x^a (1-x)^b
26
28
  * (a and b are passed separately; recovering them from a + b loses digits of the smaller one),
27
- * x^a (1-x)^b / B(a, b) = dbinom(a; a+b, x) * a b / (a + b).
29
+ * x^a (1-x)^b / B(a, b) = dbinom(a; a+b, x) * a b / (a + b). For a small shape, or a huge one with the other moderate,
30
+ * from prefactorParts (incbetPrefactor.ts) instead, as in prefactor and smallPrefactorTimes
28
31
  */
29
32
  function logPrefactor(a, b, x, xc) {
33
+ const parts = prefactorParts(a, b, x, xc);
34
+ if (parts !== undefined)
35
+ return Math.log(parts[0]) + parts[1][0] + parts[1][1];
30
36
  return dbinomRawDD(a, b, x, xc, true) + Math.log(a) + Math.log(b) - Math.log(a + b);
31
37
  }
32
38
  /** Linear value of x^a (1-x)^b / B(a, b) (0 on underflow) */
33
39
  function prefactor(a, b, x, xc) {
40
+ const parts = prefactorParts(a, b, x, xc);
41
+ if (parts !== undefined)
42
+ return parts[0] * (Math.exp(parts[1][0]) * (1 + parts[1][1]));
34
43
  return dbinomRawDD(a, b, x, xc, false) * ((a * b) / (a + b));
35
44
  }
36
45
  /** Lower limit of normal numbers. If the prefactor is larger, multiply on the linear scale */
@@ -43,6 +52,15 @@ const NORMAL_MIN = 2.2250738585072014e-308 * 1e3;
43
52
  * Returns undefined when the result underflows to 0 (the caller then works on the log scale)
44
53
  */
45
54
  function smallPrefactorTimes(a, b, x, xc, m) {
55
+ const parts = prefactorParts(a, b, x, xc);
56
+ if (parts !== undefined) {
57
+ const [ms, e] = parts;
58
+ const c = m * ms;
59
+ if (!(e[0] > -1400) || !Number.isFinite(c) || c === 0)
60
+ return undefined;
61
+ const v = Math.exp(e[0] + 700) * (1 + e[1]) * c * Math.exp(-700);
62
+ return v > 0 ? v : undefined;
63
+ }
46
64
  const { e } = dbinomExponent(a, b, x, xc);
47
65
  const c = (m * ((a * b) / (a + b))) / Math.sqrt(2 * Math.PI * a * (b / (a + b)));
48
66
  if (!(e[0] < 1400) || !Number.isFinite(c) || c === 0)
@@ -79,12 +97,16 @@ function pseriesSum(a, b, x) {
79
97
  * 1 - I = -expm1(L) - E a S, L = a log x + [lgamma(b+a) - lgamma(b)] - lgamma1p(a)
80
98
  * For small a, I is close to 1 and forming 1 - I by subtraction loses digits (1e-7 relative at a = 1e-10).
81
99
  * (Derived from the definition of the series)
100
+ * a log x and lgamma(b+a) - lgamma(b) (about a log b for a huge b) are added in double-double: for x near 1/b they
101
+ * cancel, and their rounding was 5e-14 of the result at pbeta(1.37e-272, 0.054, 3.9e270, { lowerTail: false }) (the
102
+ * latter from lgammaRatioHuge for a huge b, see there)
82
103
  */
83
104
  function pseriesComplement(a, b, xd, log) {
84
105
  const x = xd[0];
85
- const L = a * (Math.log(x) + xd[1] / x) + lgammaDiff(a, b) - lgamma1p(a);
86
- const E = Math.exp(L);
87
- const v = -Math.expm1(L) - E * a * pseriesSum(a, b, x);
106
+ const lg = b >= HUGE_SHAPE && a <= HUGE_SHAPE_MAX_SMALL ? lgammaRatioHuge(a, b) : lgammaDiffDD(a, b);
107
+ const Ld = ddAdd(ddAdd(ddMulNum(ddLog(xd), a), lg), [-lgamma1p(a), 0]);
108
+ const E = Math.exp(Ld[0]) * (1 + Ld[1]);
109
+ const v = -(Math.expm1(Ld[0]) + Ld[1] * Math.exp(Ld[0])) - E * a * pseriesSum(a, b, x);
88
110
  return log ? Math.log(v) : v;
89
111
  }
90
112
  /** Series (when b x is small and x is not close to 1). Returns I_x(a, b) */
@@ -133,7 +155,10 @@ function pseries(a, b, xd, xcd, log) {
133
155
  *
134
156
  * For the same reason a + b and b - 1 are kept in double-double: with a ≫ b, rounding a + b loses digits of b
135
157
  * (5e-11 relative at a = 1e8, b = 0.01, x = 1 - 1e-6; checked against mpmath). From 2^52 on, the steps k += 1 of
136
- * the other coefficients would be lost as well, so there every coefficient is a double-double (huge)
158
+ * the other coefficients would be lost as well, so there every coefficient is a double-double (huge). Below 2^52 the
159
+ * same holds for a non-integer a just below a power of two: a + 1, a + 2, ... cross into the next binade, where a's
160
+ * last bit no longer fits, and every coefficient after that is rounded the same way. The error grows with a (log P
161
+ * off by 3e-8 at a = 2^40 - 2^-13, 1.3e-4 at a = 2^52 - 0.5); see stepsInexact
137
162
  */
138
163
  // ddDiv for the loop of the continued fraction without allocating: the same operations as in dd.ts, with the
139
164
  // result left in R (a typed array, so that storing it allocates nothing). Generated with python3 scripts/ddgen.py scalar
@@ -209,9 +234,22 @@ function sDiv(ah, al, bh, bl) {
209
234
  R[0] = s66;
210
235
  R[1] = e67;
211
236
  }
237
+ /** The continued fractions stop after 100000 steps, where the largest coefficient is a + 2 * 100000 + 2 */
238
+ const CF_SPAN = 200002;
239
+ /**
240
+ * Whether the steps a + 1, a + 2, ... of the continued fraction are not all exact in double (a < 2^52). They are all
241
+ * exact when a + CF_SPAN is (the ulp only grows along the way), which for a > CF_SPAN is (a + CF_SPAN) - a === CF_SPAN.
242
+ * Only from 2^20 on: below, the rounding of the steps (relative ε/2) moves the result by about an ulp (against the
243
+ * double-double steps: 2e-16 on log P at a = 2^20, 7e-16 at 2^25), and the slower double-double steps would be taken
244
+ * by most non-integer a (a + CF_SPAN crosses a binade for every a below 2^17)
245
+ */
246
+ function stepsInexact(a) {
247
+ return a >= 2 ** 20 && a < 2 ** 52 && a + CF_SPAN - a !== CF_SPAN;
248
+ }
212
249
  function continuedFractionCore(a, b, xd, xcd, second) {
213
- if (!isDoubleDouble() || Math.max(a, b) >= 2 ** 52)
250
+ if (!isDoubleDouble() || Math.max(a, b) >= 2 ** 52 || stepsInexact(a)) {
214
251
  return continuedFractionCoreOps(a, b, xd, xcd, second);
252
+ }
215
253
  // The loop of continuedFractionCoreOps below on local variables, without allocating [hi, lo] arrays: the same
216
254
  // operations in the same order, so the result is bit-identical. Generated with python3 scripts/ddgen.py cf
217
255
  let zh = xd[0];
@@ -590,7 +628,9 @@ function continuedFractionCore(a, b, xd, xcd, second) {
590
628
  function continuedFractionCoreOps(a, b, xd, xcd, second) {
591
629
  // #1: coefficients use x; #2: coefficients use z = x/(1-x)
592
630
  const z = second ? ddDiv(xd, xcd) : xd;
593
- const huge = Math.max(a, b) >= 2 ** 52;
631
+ const huge = Math.max(a, b) >= 2 ** 52 || stepsInexact(a);
632
+ // Above 1e150 the products of two of the parameters (h3 h4 = a (a + 1), ...) overflow: divide before multiplying
633
+ const vast = Math.max(a, b) > 1e150;
594
634
  // Partial numerators k1 x k2 / (k3 k4) and k5 x k6 / (k7 k8). k1, k3, k4, k7, k8 are doubles, with
595
635
  // double-double copies (h1, ...) that are used and advanced only when huge
596
636
  let k1 = a;
@@ -613,16 +653,20 @@ function continuedFractionCoreOps(a, b, xd, xcd, second) {
613
653
  let qkm1 = [1, 0];
614
654
  let ans = [1, 0];
615
655
  for (let n = 0; n < 100000; n++) {
616
- let xk = huge
617
- ? ddDiv(ddMul(ddMul(z, h1), k2), ddMul(h3, h4))
618
- : ddDiv(ddMul(ddMulNum(z, k1), k2), twoProd(k3, k4));
656
+ let xk = vast
657
+ ? ddMul(ddMul(z, ddDiv(h1, h3)), ddDiv(k2, h4))
658
+ : huge
659
+ ? ddDiv(ddMul(ddMul(z, h1), k2), ddMul(h3, h4))
660
+ : ddDiv(ddMul(ddMulNum(z, k1), k2), twoProd(k3, k4));
619
661
  let pk = ddSub(pkm1, ddMul(pkm2, xk));
620
662
  let qk = ddSub(qkm1, ddMul(qkm2, xk));
621
663
  pkm2 = pkm1;
622
664
  pkm1 = pk;
623
665
  qkm2 = qkm1;
624
666
  qkm1 = qk;
625
- xk = ddDiv(ddMul(ddMulNum(z, k5), k6), huge ? ddMul(h7, h8) : twoProd(k7, k8));
667
+ xk = vast
668
+ ? ddMul(ddMulNum(z, k5), ddDiv(ddDiv(k6, h7), h8))
669
+ : ddDiv(ddMul(ddMulNum(z, k5), k6), huge ? ddMul(h7, h8) : twoProd(k7, k8));
626
670
  pk = ddAdd(pkm1, ddMul(pkm2, xk));
627
671
  qk = ddAdd(qkm1, ddMul(qkm2, xk));
628
672
  pkm2 = pkm1;
@@ -673,9 +717,16 @@ function continuedFractionCoreOps(a, b, xd, xcd, second) {
673
717
  function pseriesOk(a, b, x) {
674
718
  return b * x <= 1 && x <= 0.95;
675
719
  }
676
- /** Whether to compute I_x(a, b) by continued fraction in frame (a, b, x) (below the mean, as in xsf) */
677
- function cfOk(a, b, x) {
678
- return x <= a / (a + b);
720
+ /**
721
+ * Whether to compute I_x(a, b) by continued fraction in frame (a, b, x) (below the mean, as in xsf). Above x = 1/2 the
722
+ * test is 1 - x >= b/(a + b), on the smaller sides: x and the mean can both round to 1 (pnbinom(2.6e200, 3.1e287,
723
+ * { mu: 195.6 }) has 1 - x = 6.3e-286 against b/(a + b) = 8.5e-88, and the continued fraction above the mean was NaN)
724
+ */
725
+ function cfOk(a, b, x, xc) {
726
+ if (x[0] <= 0.5)
727
+ return x[0] <= a / (a + b);
728
+ // (b/(a + b) as 1/(1 + a/b) where a + b overflows)
729
+ return xc[0] >= (a + b < Infinity ? b / (a + b) : 1 / (1 + a / b));
679
730
  }
680
731
  /** Compute I_x(a, b) by continued fraction */
681
732
  function continuedFraction(a, b, xd, xcd, log) {
@@ -744,33 +795,61 @@ export function betaIncBoth(a, b, x, xc, lower) {
744
795
  const xcd = x <= xc ? twoSum(1, -x) : [xc, 0];
745
796
  return betaIncCore(a, b, xd, xcd, lower, true);
746
797
  }
798
+ const DBL_MIN = 2.2250738585072014e-308;
799
+ /**
800
+ * I_x(a, b) (lower) or 1 - I_x(a, b) for x below DBL_MIN, from x and lx = log x in double-double (x itself may have
801
+ * underflowed to 0, as in the F distribution far out: only lx then carries it), as [log, linear] (log NaN unless
802
+ * wantLog). From the series I_x(a, b) = x^a / (a B(a, b)) (1 + a S), S = pseriesSum(a, b, x): the terms of S are about
803
+ * (-b x)^n / n!, and b x is at most 4 here (b near the largest double), mostly negligible.
804
+ * log(1/(a B(a, b))) is lgamma(a+b) - lgamma(b) - lgamma(a+1) without subtraction, or for a small shape
805
+ * log(b/(a + b)) + log Γ(1+a+b)/(Γ(1+a) Γ(1+b)) with the ratio r = b/(a + b) kept on the linear scale (as a log, its
806
+ * rounding of ε |log r| would become the relative error of the result)
807
+ */
808
+ export function betaIncTinyX(a, b, x, lx, lower, wantLog) {
809
+ const c = Math.log1p(a * pseriesSum(a, b, x));
810
+ let r = 1;
811
+ let lr = 0;
812
+ let e;
813
+ if (Math.min(a, b) < SMALL_SHAPE) {
814
+ const q = Math.min(a, b) / Math.max(a, b);
815
+ [r, lr] = a <= b ? [1 / (1 + q), -Math.log1p(q)] : [q / (1 + q), Math.log(q) - Math.log1p(q)];
816
+ e = ddAdd(ddAdd(ddMulNum(lx, a), smallShapeG(a, b)), [c, 0]);
817
+ }
818
+ else {
819
+ const lg = b >= HUGE_SHAPE && a <= HUGE_SHAPE_MAX_SMALL ? lgammaRatioHuge(a, b) : lgammaDiffDD(a, b);
820
+ e = ddAdd(ddAdd(ddMulNum(lx, a), lg), [c - lgamma1p(a), 0]);
821
+ }
822
+ const lt = lr + e[0] + e[1];
823
+ const v = r * (Math.exp(e[0]) * (1 + e[1]));
824
+ if (lower)
825
+ return [lt, v];
826
+ // The other tail: -expm1(lt), and its log from v where v is small (lt rounded to a double is off by up to ε |lt|,
827
+ // which would become the relative error of the result for |lt| > 700) and from -expm1(lt) where v is close to 1
828
+ // (log1p(-v) would lose the digits of 1 - v: 1 - I is -Infinity for x = 5e-324 at a = 5.7e-37)
829
+ return [wantLog ? (lt < -Math.LN2 ? Math.log1p(-v) : Math.log(-Math.expm1(lt))) : NaN, -Math.expm1(lt)];
830
+ }
747
831
  /**
748
832
  * Core of betaIncDD. Returns [log, linear]. The linear value is always computed; the log only when wantLog
749
833
  * (otherwise the log slot is NaN). The log is log(v) of the linear value v; if v exceeds 1/2 the other side is
750
- * computed directly and log1p is used, and if v is close to subnormal it is recomputed on the spot
834
+ * computed directly and log1p is used, and if v is close to subnormal it is recomputed on the spot.
835
+ * A value within rounding of 1 can come out an ulp above it (from the product of a prefactor and a series near 1:
836
+ * pbeta(0.615, 2, 2.7e-158, { lowerTail: false }) was 1.0000000000000002), so it is capped at 1 (log at 0)
751
837
  */
752
838
  function betaIncCore(a, b, xd, xcd, lower, wantLog) {
839
+ const r = betaIncUncapped(a, b, xd, xcd, lower, wantLog);
840
+ return r[1] > 1 || r[0] > 0 ? [Math.min(r[0], 0), Math.min(r[1], 1)] : r;
841
+ }
842
+ function betaIncUncapped(a, b, xd, xcd, lower, wantLog) {
753
843
  if (xd[0] <= 0)
754
844
  return lower ? [-Infinity, 0] : [0, 1];
755
845
  if (xcd[0] <= 0)
756
846
  return lower ? [0, 1] : [-Infinity, 0];
757
- // x (or 1 - x) is subnormal: the first series term I_x(a, b) ≈ x^a / (a B(a, b)) suffices (relative error about x).
758
- // The binomial-probability helpers break down on products of subnormals, so build this region directly in logs
759
- const DBL_MIN = 2.2250738585072014e-308;
760
- if (xd[0] < DBL_MIN || xcd[0] < DBL_MIN) {
761
- const small = xd[0] < DBL_MIN;
762
- const [sa, sb, sx] = small ? [a, b, xd] : [b, a, xcd];
763
- // log(1/(a B(a, b))) = lgamma(a+b) - lgamma(b) - lgamma(a+1), without subtraction
764
- const e = ddAdd(ddMulNum(ddLog(sx), sa), [lgammaDiff(sa, sb) - lgamma1p(sa), 0]);
765
- const lt = e[0] + e[1]; // log of the smaller tail (the lower tail if small)
766
- const own = small === lower;
767
- const v = Math.exp(e[0]) * (1 + e[1]);
768
- if (own)
769
- return [lt, v];
770
- // The log of the other tail from v, not from exp(lt): lt rounded to a double is off by up to ε |lt| (|lt| > 700),
771
- // which would become the relative error of the result
772
- return [wantLog ? Math.log1p(-v) : NaN, -Math.expm1(lt)];
773
- }
847
+ // x (or 1 - x) is subnormal: the series with its prefactor in logs (betaIncTinyX). The binomial-probability helpers
848
+ // break down on products of subnormals
849
+ if (xd[0] < DBL_MIN)
850
+ return betaIncTinyX(a, b, xd[0], ddLog(xd), lower, wantLog);
851
+ if (xcd[0] < DBL_MIN)
852
+ return betaIncTinyX(b, a, xcd[0], ddLog(xcd), !lower, wantLog);
774
853
  // Both parameters large and x near the mean: the uniform asymptotic expansion, whose cost does not grow with
775
854
  // the parameters (the continued fraction needs about sqrt(a + b) steps there)
776
855
  if (a >= TEMME_MIN_M && b >= TEMME_MIN_M) {
@@ -784,7 +863,12 @@ function betaIncCore(a, b, xd, xcd, lower, wantLog) {
784
863
  // large a (incbetLargeA.ts) instead, in the frame of the large parameter. The length of the continued fraction
785
864
  // stops growing with the large parameter, but in the bulk it takes 30 to 170 double-double steps; the expansion
786
865
  // takes a few terms
787
- const largeA = Math.max(a, b) >= LARGE_A_MIN && Math.min(a, b) <= SMALL_B_MAX;
866
+ // Also for a larger small parameter (up to 1e4, as the expansion takes about b/2 steps) where x rounds to 1 in the
867
+ // frame of the large one (then l = -log x is below ε and the terms after the leading Q(b, u) or P(b, u) vanish):
868
+ // the continued fraction is NaN there (pnbinom(1.9e153, 44.4, { prob: 1.6e-149, lowerTail: false }))
869
+ const largeA = Math.max(a, b) >= LARGE_A_MIN &&
870
+ (Math.min(a, b) <= SMALL_B_MAX ||
871
+ ((a >= b ? xd[0] : xcd[0]) === 1 && Math.min(a, b) <= 1e4 && Math.min(a, b) < 1e-8 * Math.max(a, b)));
788
872
  const viaLargeA = (low, log) => {
789
873
  if (!largeA)
790
874
  return undefined;
@@ -808,12 +892,16 @@ function betaIncCore(a, b, xd, xcd, lower, wantLog) {
808
892
  if (pseriesOk(pa, pb, px[0])) {
809
893
  const v = pseriesComplement(pa, pb, px, false);
810
894
  // Cancellation check as for the requested tail (see below)
811
- if (pa * Math.abs(Math.log(px[0])) > 32 * v && cfOk(oa, ob, ox[0])) {
812
- return viaLargeA(!lower, false)?.[1] ?? continuedFraction(oa, ob, ox, oxc, false);
895
+ if (pa * Math.abs(Math.log(px[0])) > 32 * v) {
896
+ const e = viaLargeA(!lower, false)?.[1];
897
+ if (e !== undefined)
898
+ return e;
899
+ if (ox[0] < 1 && cfOk(oa, ob, ox, oxc))
900
+ return continuedFraction(oa, ob, ox, oxc, false);
813
901
  }
814
902
  return v;
815
903
  }
816
- if (cfOk(oa, ob, ox[0]))
904
+ if (cfOk(oa, ob, ox, oxc))
817
905
  return viaLargeA(!lower, false)?.[1] ?? continuedFraction(oa, ob, ox, oxc, false);
818
906
  return undefined;
819
907
  };
@@ -823,30 +911,48 @@ function betaIncCore(a, b, xd, xcd, lower, wantLog) {
823
911
  const v = pseries(pa, pb, px, pxc, false);
824
912
  if (wantLog && v < TINY)
825
913
  return [pseries(pa, pb, px, pxc, true), v];
914
+ // Above 1/2 with the series applying in the other frame too: 1 minus the other tail, which is accurate to about an
915
+ // ulp, while this series near x = 0.95 sums hundreds of terms whose products round (pbeta(0.9398, 0.0209, 0.723)
916
+ // and its upper tail added up to 1 - 2e-15)
917
+ if (v > 0.5 && pseriesOk(oa, ob, ox[0])) {
918
+ const o = pseries(oa, ob, ox, oxc, false);
919
+ return [wantLog ? Math.log1p(-o) : NaN, 1 - o];
920
+ }
826
921
  return finish(v, otherDirect);
827
922
  }
828
923
  if (pseriesOk(oa, ob, ox[0])) {
924
+ // Where the other tail is below 1/2, 1 minus it is accurate to about an ulp, while the exponent of
925
+ // pseriesComplement rounds at ε (|a log x| + |lgamma(b + a) - lgamma(b)| + |lgamma(a + 1)|), terms that cancel
926
+ // (pbinom(20, 21, 0.9265) was 0.7985148925910792, 2e-15 above 1 - prob^21)
927
+ const o = pseries(oa, ob, ox, oxc, false);
928
+ if (o < 0.5)
929
+ return [wantLog ? Math.log1p(-o) : NaN, 1 - o];
829
930
  const v = pseriesComplement(oa, ob, ox, false);
830
931
  // The exponent L of pseriesComplement is a sum of terms of size a |log x| that can cancel, and their rounding
831
932
  // (absolute, about ε a |log x|) is then large relative to a small result (1e-14 at a = 0.01, b = 1e4, x = 1e-4).
832
- // When a |log x| exceeds the result 32 times and the continued fraction applies in this tail's frame, use it
833
- // instead (a lower threshold would also send cases where the series is accurate, e.g. most of pt near 0, to the
834
- // slower continued fraction)
835
- if (oa * Math.abs(Math.log(ox[0])) > 32 * v && cfOk(pa, pb, px[0])) {
933
+ // When a |log x| exceeds the result 32 times, use the expansion for large a where it applies, or the continued
934
+ // fraction where it applies in this tail's frame (a lower threshold would also send cases where the series is
935
+ // accurate, e.g. most of pt near 0, to the slower continued fraction). The expansion does not need the continued
936
+ // fraction's side of the mean (the upper tail of pbeta(5.6e-161, 0.82, 1.5e160) was off by 8e-14 from the series)
937
+ // (The continued fraction not when x rounds to 1 in this frame, with 1 - x below ε, e.g. pnbinom with size 6e178:
938
+ // it is then NaN, and the exponent is so negative that the series value is 1 to double precision)
939
+ if (oa * Math.abs(Math.log(ox[0])) > 32 * v) {
836
940
  const e = viaLargeA(lower, wantLog);
837
941
  if (e !== undefined)
838
942
  return e;
839
- const w = continuedFraction(pa, pb, px, pxc, false);
840
- if (wantLog && w < TINY)
841
- return [continuedFraction(pa, pb, px, pxc, true), w];
842
- return finish(w, otherDirect);
943
+ if (px[0] < 1 && cfOk(pa, pb, px, pxc)) {
944
+ const w = continuedFraction(pa, pb, px, pxc, false);
945
+ if (wantLog && w < TINY)
946
+ return [continuedFraction(pa, pb, px, pxc, true), w];
947
+ return finish(w, otherDirect);
948
+ }
843
949
  }
844
- return finish(v, () => pseries(oa, ob, ox, oxc, false));
950
+ return finish(v, () => o);
845
951
  }
846
952
  const e = viaLargeA(lower, wantLog);
847
953
  if (e !== undefined)
848
954
  return e;
849
- if (cfOk(pa, pb, px[0])) {
955
+ if (cfOk(pa, pb, px, pxc)) {
850
956
  const v = continuedFraction(pa, pb, px, pxc, false);
851
957
  if (wantLog && v < TINY)
852
958
  return [continuedFraction(pa, pb, px, pxc, true), v];