@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
@@ -70,8 +70,43 @@ export function dtDensity1(x, df, log) {
70
70
  }
71
71
  return dtCore(x, df, log);
72
72
  }
73
+ /** Below this n the upper tail is 1/2 - tinyDfDelta (the next terms are under 1e-23 absolute) */
74
+ const TINY_DF = 1e-15;
75
+ /**
76
+ * P[0 < T < t] (t > 0) for n < TINY_DF: (n/2) asinh(t / sqrt(n)). With a = n/2 and y = t^2/(n + t^2),
77
+ * P[|T| < t] = I_y(1/2, a), where 1/B(1/2, a) = a (1 + O(a)) and the integrand u^(-1/2) (1 - u)^(a-1) is
78
+ * u^(-1/2) / (1 - u) (1 + O(a log(1 - u))), whose integral over [0, y] is 2 atanh(sqrt(y)) = 2 asinh(t / sqrt(n)).
79
+ * The relative error is O(n log(t^2/n)), below n^2 log^2(t^2/n) < 1e-23 absolute. The incomplete beta function's
80
+ * series loses digits for so small an a (pt(-5.05, 2.4e-242) was 0.49999999999998995, 0.5 further out)
81
+ */
82
+ function tinyDfDelta(t, n) {
83
+ const r = t / Math.sqrt(n);
84
+ // asinh(r) = log(2 r) + O(r^-2) where r overflows
85
+ return 0.5 * n * (r < 1e300 ? Math.asinh(r) : Math.LN2 + Math.log(t) - 0.5 * Math.log(n));
86
+ }
87
+ /**
88
+ * x = n/(n + t^2) and 1 - x = t^2/(n + t^2) in double-double. Where t^2 or n is beyond the range of Veltkamp
89
+ * splitting (the products in ddDiv overflowed to NaN: pt(-3.5e151, 4.3e121)), both are first scaled by the same power
90
+ * of 2, 2^-2m with 2^m >= max(t, sqrt(n)) (exact unless t^2 / n is so small that 1 - x does not matter)
91
+ */
92
+ function betaArgs(t, n) {
93
+ let tt = t;
94
+ let nn = n;
95
+ if (t > 1e150 || n > 1e290) {
96
+ const f = 2 ** -Math.ceil(Math.log2(Math.max(t, Math.sqrt(n))));
97
+ tt = t * f;
98
+ nn = n * f * f;
99
+ }
100
+ const t2d = twoProd(tt, tt);
101
+ const den = ddAdd(t2d, [nn, 0]);
102
+ return [ddDiv([nn, 0], den), ddDiv(t2d, den)];
103
+ }
73
104
  /** Log or value of P[T > t] (t > 0): half of s = P[|T| > t] = I_{n/(n+t^2)}(n/2, 1/2) */
74
105
  function upperTailPositive(t, n, log) {
106
+ if (n < TINY_DF) {
107
+ const d = tinyDfDelta(t, n);
108
+ return log ? Math.log1p(-2 * d) - Math.LN2 : 0.5 - d;
109
+ }
75
110
  const t2 = t * t;
76
111
  const x = n / (n + t2);
77
112
  if (!(x > 1e-250)) {
@@ -82,14 +117,14 @@ function upperTailPositive(t, n, log) {
82
117
  const e = ddAdd(ddMulNum(lx, n / 2), [-Math.log(n / 2) - lbeta(n / 2, 0.5) - Math.LN2, 0]);
83
118
  return log ? e[0] + e[1] : Math.exp(e[0]) * (1 + e[1]);
84
119
  }
85
- // Form x = n/(n + t^2) and 1 - x = t^2/(n + t^2) in double-double
86
- const t2d = twoProd(t, t);
87
- const den = ddAdd(t2d, [n, 0]);
88
- const s = betaIncDD(n / 2, 0.5, ddDiv([n, 0], den), ddDiv(t2d, den), true, log);
120
+ const [x1, y1] = betaArgs(t, n);
121
+ const s = betaIncDD(n / 2, 0.5, x1, y1, true, log);
89
122
  return log ? s - Math.LN2 : s / 2;
90
123
  }
91
124
  /** [log, linear] of upperTailPositive (each value identical to upperTailPositive) */
92
125
  function upperTailPositiveBoth(t, n) {
126
+ if (n < TINY_DF)
127
+ return [upperTailPositive(t, n, true), upperTailPositive(t, n, false)];
93
128
  const t2 = t * t;
94
129
  const x = n / (n + t2);
95
130
  if (!(x > 1e-250)) {
@@ -97,9 +132,8 @@ function upperTailPositiveBoth(t, n) {
97
132
  const e = ddAdd(ddMulNum(lx, n / 2), [-Math.log(n / 2) - lbeta(n / 2, 0.5) - Math.LN2, 0]);
98
133
  return [e[0] + e[1], Math.exp(e[0]) * (1 + e[1])];
99
134
  }
100
- const t2d = twoProd(t, t);
101
- const den = ddAdd(t2d, [n, 0]);
102
- const s = betaIncBothDD(n / 2, 0.5, ddDiv([n, 0], den), ddDiv(t2d, den), true);
135
+ const [x1, y1] = betaArgs(t, n);
136
+ const s = betaIncBothDD(n / 2, 0.5, x1, y1, true);
103
137
  return [s[0] - Math.LN2, s[1] / 2];
104
138
  }
105
139
  export function pt1(q, df, lowerTail, logP) {
@@ -140,10 +174,14 @@ export function qt1(p, df, lowerTail, logP) {
140
174
  let x0;
141
175
  // log t from the tail asymptotic P[T > t] ≈ n^(n/2) t^(-n) / (n B(n/2, 1/2))
142
176
  const lx0 = (0.5 * n * Math.log(n) - Math.log(n) - lbeta(n / 2, 0.5) - logTarget) / n;
143
- // ±Inf if the answer exceeds the largest double (t is large there and the asymptotic form is accurate)
144
- if (lx0 > 709.78)
177
+ // ±Inf if the answer exceeds the largest double (t is large there and the asymptotic form is accurate); near that
178
+ // decided by the tail at the largest double itself (a fixed 709.78 gave -Infinity for qt(3.048e-196, 0.633), whose
179
+ // answer is -1.79e308)
180
+ if (lx0 > 709.79 || (lx0 > 709.77 && upperTailPositive(Number.MAX_VALUE, n, true) > logTarget))
145
181
  return lower ? -Infinity : Infinity;
146
- if (logTarget < -30) {
182
+ // The asymptotic form needs t^2 >> n; for large n the tail stays normal-like far out (t^2 < n), where it would
183
+ // start Newton near sqrt(n) (qt(1.6e-243, 1e120) converged to -1.13 from there)
184
+ if (logTarget < -30 && 2 * lx0 > Math.log(n) + 1) {
147
185
  x0 = Math.exp(lx0);
148
186
  }
149
187
  else {
@@ -3,25 +3,46 @@
3
3
  // Written for rStats.js (no ported code). With w = b - a:
4
4
  // f(x) = 2 (x - a) / (w (c - a)) left of c, 2 (b - x) / (w (b - c)) right of it;
5
5
  // P[X <= x] = (x - a)^2 / (w (c - a)) left of c, P[X > x] = (b - x)^2 / (w (b - c)) right of it.
6
- // Each tail is computed from its own end, and the quantile from the tail it falls in.
6
+ // Each tail is computed from its own end, and the quantile from the tail it falls in. Products are formed from ratios
7
+ // of lengths (each at most 1), so that wide and narrow intervals neither overflow nor underflow on the way.
7
8
  import { vectorize } from "../internal/vectorize.js";
8
9
  import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
9
10
  const valid = (a, b, c) => Number.isFinite(a) && Number.isFinite(b) && a < b && a <= c && c <= b;
11
+ /** 1/2 when b - a overflows (x, a, b and c are all halved then; the probabilities do not change), else 1 */
12
+ const halfIfOverflow = (a, b) => (Number.isFinite(b - a) ? 1 : 0.5);
10
13
  export function dtriang1(x, a, b, c, log) {
11
14
  if (Number.isNaN(x) || !valid(a, b, c))
12
15
  return NaN;
13
16
  if (x < a || x > b)
14
17
  return d0(log);
18
+ const h = halfIfOverflow(a, b);
19
+ if (h !== 1) {
20
+ const d = dtriang1(x * h, a * h, b * h, c * h, log);
21
+ return log ? d + Math.log(h) : d * h;
22
+ }
15
23
  const w = b - a;
16
- if (x === c)
17
- return log ? Math.log(2 / w) : 2 / w;
18
- // the density is (2 / w) (1 - r), r the fraction of the way from the mode to the end on x's side; near the mode
19
- // 1 - r from r (x - c is exact there), elsewhere from the distance to the end
20
- const r = x < c ? (c - x) / (c - a) : (x - c) / (b - c);
24
+ // The density is (2 / w) s with s = (x - a) / (c - a) left of the mode, (b - x) / (b - c) right of it (s <= 1, so
25
+ // nothing over- or underflows on the way unless the density itself does). Near the mode s = 1 - r with r the
26
+ // fraction of the way from the mode to the end on x's side (x - c is exact there)
27
+ const r = x === c ? 0 : x < c ? (c - x) / (c - a) : (x - c) / (b - c);
21
28
  if (r < 0.5)
22
- return log ? Math.log(2 / w) + Math.log1p(-r) : (2 / w) * (1 - r);
23
- const d = x < c ? (2 * (x - a)) / (w * (c - a)) : (2 * (b - x)) / (w * (b - c));
24
- return log ? Math.log(d) : d;
29
+ return log ? Math.LN2 - Math.log(w) + Math.log1p(-r) : (2 * (1 - r)) / w;
30
+ const s = x < c ? (x - a) / (c - a) : (b - x) / (b - c);
31
+ return log ? Math.LN2 - Math.log(w) + Math.log(s) : (2 * s) / w;
32
+ }
33
+ /**
34
+ * The tails [lower, upper] at a < q < b (b - a finite), from ratios of lengths that are at most 1, and the log of the
35
+ * near tail (the one from the end on q's side of the mode) as a sum of logs, which stays exact where the tail is subnormal
36
+ */
37
+ function tails(q, a, b, c) {
38
+ const w = b - a;
39
+ // the far tail as a sum of positive terms: 1 - (q - a)^2 / (w (c - a)) = (b - c) / w + (c - q)(q - a + c - a) / (w (c - a))
40
+ if (q <= c) {
41
+ const [s, t] = [(q - a) / (c - a), (q - a) / w];
42
+ return [s * t, (b - c) / w + ((c - q) / (c - a)) * (t + (c - a) / w), Math.log(s) + Math.log(t)];
43
+ }
44
+ const [s, t] = [(b - q) / (b - c), (b - q) / w];
45
+ return [(c - a) / w + ((q - c) / (b - c)) * (t + (b - c) / w), s * t, Math.log(s) + Math.log(t)];
25
46
  }
26
47
  export function ptriang1(q, a, b, c, lowerTail, logP) {
27
48
  if (Number.isNaN(q) || !valid(a, b, c))
@@ -30,23 +51,16 @@ export function ptriang1(q, a, b, c, lowerTail, logP) {
30
51
  return dt0(lowerTail, logP);
31
52
  if (q >= b)
32
53
  return dt1(lowerTail, logP);
33
- const w = b - a;
34
- // the far tail as a sum of positive terms: 1 - (q - a)^2 / (w (c - a)) = (b - c) / w + (c - q)(q + c - 2a) / (w (c - a))
35
- let lower;
36
- let upper;
37
- if (q <= c) {
38
- lower = ((q - a) * (q - a)) / (w * (c - a));
39
- upper = (b - c) / w + ((c - q) * (q - a + (c - a))) / (w * (c - a));
40
- }
41
- else {
42
- upper = ((b - q) * (b - q)) / (w * (b - c));
43
- lower = (c - a) / w + ((q - c) * (b - q + (b - c))) / (w * (b - c));
44
- }
45
- const v = lowerTail ? lower : upper;
54
+ const h = halfIfOverflow(a, b);
55
+ const [lower, upper, lnear] = tails(q * h, a * h, b * h, c * h);
56
+ // The sum of positive terms can round an ulp above 1
57
+ const v = Math.min(lowerTail ? lower : upper, 1);
46
58
  if (!logP)
47
59
  return v;
48
- // the log of a probability above 1/2 from the other tail
49
- return v > 0.5 ? Math.log1p(-(lowerTail ? upper : lower)) : Math.log(v);
60
+ // the log of a probability above 1/2 from the other tail; a subnormal near tail from its factors
61
+ if (v > 0.5)
62
+ return Math.log1p(-(lowerTail ? upper : lower));
63
+ return v < 2 ** -1022 && lowerTail === q <= c ? lnear : Math.log(v);
50
64
  }
51
65
  export function qtriang1(p, a, b, c, lowerTail, logP) {
52
66
  if (Number.isNaN(p) || !valid(a, b, c))
@@ -54,13 +68,38 @@ export function qtriang1(p, a, b, c, lowerTail, logP) {
54
68
  const bd = quantileBoundaries(p, a, b, lowerTail, logP);
55
69
  if (bd !== undefined)
56
70
  return bd;
71
+ const h = halfIfOverflow(a, b);
72
+ if (h !== 1)
73
+ return qtriang1(p, a * h, b * h, c * h, lowerTail, logP) / h;
57
74
  const w = b - a;
58
75
  const pv = logP ? Math.exp(p) : p;
76
+ // sqrt of the tail on the side of p; exp(p / 2) where exp(p) is subnormal
77
+ const sqrtP = logP && pv < 2 ** -1022 ? Math.exp(p / 2) : Math.sqrt(pv);
59
78
  const lower = lowerTail ? pv : logP ? -Math.expm1(p) : 1 - p;
60
79
  const upper = lowerTail ? (logP ? -Math.expm1(p) : 1 - p) : pv;
61
- if (lower <= (c - a) / w)
62
- return a + Math.sqrt(lower * w * (c - a));
63
- return b - Math.sqrt(upper * w * (b - c));
80
+ // Left of the mode x - a = (c - a) sqrt(t) with t = lower w / (c - a), the share of the left part's probability;
81
+ // right of it b - x = (b - c) sqrt(t), t = upper w / (b - c). Near the mode (t > 1/2) the distance from it instead,
82
+ // (1 - sqrt(t)) = (1 - t) / (1 + sqrt(t)) with 1 - t from the other tail (for c = a or c = b that tail itself, so
83
+ // no cancellation near the end). The square roots are taken factor by factor so that no product over- or underflows
84
+ const cl = (c - a) / w;
85
+ const cr = (b - c) / w;
86
+ let x;
87
+ if (cl > 0 && lower <= cl) {
88
+ const t = (lower / (c - a)) * w;
89
+ x =
90
+ t <= 0.5
91
+ ? a + (lowerTail ? sqrtP : Math.sqrt(lower)) * Math.sqrt(w) * Math.sqrt(c - a)
92
+ : c - ((c - a) * ((upper - cr) / cl)) / (1 + Math.sqrt(t));
93
+ }
94
+ else {
95
+ const t = (upper / (b - c)) * w;
96
+ x =
97
+ t <= 0.5
98
+ ? b - (lowerTail ? Math.sqrt(upper) : sqrtP) * Math.sqrt(w) * Math.sqrt(b - c)
99
+ : c + ((b - c) * ((lower - cl) / cr)) / (1 + Math.sqrt(t));
100
+ }
101
+ // Rounding must not take x out of the support
102
+ return Math.min(Math.max(x, a), b);
64
103
  }
65
104
  /**
66
105
  * Density of the triangular distribution. Equivalent to `extraDistr::dtriang(x, a = -1, b = 1, c = (a + b)/2, log = FALSE)` in R.
@@ -17,12 +17,11 @@
17
17
  // interpolants in log w (speeds up the outer integral, the quantile search, and repeated calls with the same nmeans)
18
18
  // - The outer integral is over v = log(t/a), t = df s^2 / 2 ~ Gamma(a = df/2), with the density in Loader's form
19
19
  // (stirlerr and bd0 = a (e^v - 1 - v)). When the result is below 1e-290, it is recomputed with a version that
20
- // keeps the integrand on the log scale (u = log t, dpoisRaw)
20
+ // keeps the integrand on the log scale
21
21
  // Quantiles solve for the log probability of the smaller tail in log q with Brent's method.
22
22
  import { vectorize } from "../internal/vectorize.js";
23
23
  import { dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
24
- import { dpoisRaw, stirlerr } from "../special/loader.js";
25
- import { lgamma } from "../special/gamma.js";
24
+ import { stirlerr } from "../special/loader.js";
26
25
  import { pnorm } from "./normal.js";
27
26
  // ---- Clenshaw-Curtis rule (convergence judged from the Chebyshev coefficients) ----
28
27
  //
@@ -33,6 +32,8 @@ import { pnorm } from "./normal.js";
33
32
  // this test is reliable.
34
33
  const CC_MAX = 128;
35
34
  const EPS = Number.EPSILON;
35
+ /** Upper bound on the number of intervals of one integral (smooth integrands need a few dozen) */
36
+ const MAX_PIECES = 256;
36
37
  /** Table of cos(π m / CC_MAX) (m = 0..2 CC_MAX) */
37
38
  const COS_TABLE = Float64Array.from({ length: 2 * CC_MAX + 1 }, (_, m) => Math.cos((Math.PI * m) / CC_MAX));
38
39
  /** Weights of the N-point Clenshaw-Curtis rule (interval [-1, 1], nodes cos(jπ/N)) */
@@ -82,6 +83,7 @@ class CCPiece {
82
83
  f;
83
84
  a;
84
85
  b;
86
+ noise;
85
87
  c;
86
88
  h;
87
89
  values = new Float64Array(CC_MAX + 1);
@@ -89,10 +91,13 @@ class CCPiece {
89
91
  N = 0;
90
92
  integral = 0;
91
93
  error = Infinity;
92
- constructor(f, a, b) {
94
+ constructor(f, a, b,
95
+ /** Relative noise of the values of f (the error estimate does not go below it) */
96
+ noise) {
93
97
  this.f = f;
94
98
  this.a = a;
95
99
  this.b = b;
100
+ this.noise = noise;
96
101
  this.c = 0.5 * (a + b);
97
102
  this.h = 0.5 * (b - a);
98
103
  }
@@ -111,19 +116,23 @@ class CCPiece {
111
116
  const res = chebyshev(v, N);
112
117
  this.N = N;
113
118
  this.integral = res.integral * this.h;
114
- // Truncation error is about trailing coefficient × Σ 2/m^2 ≈ trailing × 4/N. Do not go below rounding error
115
- this.error = Math.max((res.tail * 4) / N, 4 * EPS * res.scale) * Math.abs(this.h);
119
+ // Truncation error is about trailing coefficient × Σ 2/m^2 ≈ trailing × 4/N. Do not go below the noise of the values
120
+ this.error = Math.max((res.tail * 4) / N, this.noise * res.scale) * Math.abs(this.h);
116
121
  }
117
122
  }
118
123
  /**
119
124
  * Integrate f over the sequence of intervals edges (ascending). First compute each interval with 16 points to
120
125
  * estimate the magnitude of the integral, then double the points until each interval's error estimate is at most
121
- * relTol × |total| / (number of intervals) (bisecting if 128 points are not enough).
126
+ * relTol × |total| / (number of intervals) (bisecting if 128 points are not enough). noise is the relative error of
127
+ * the values of f: an interval whose error estimate is at that level is accepted, since refining it cannot make the
128
+ * estimate smaller (the noise shows up in the trailing coefficients at any width). Without it, an integrand computed
129
+ * as exp(lf - M) with |lf| in the thousands (noise ε |lf|) was bisected down to the round limit at every call. The
130
+ * number of intervals is bounded as well, so that the work stays bounded whatever the integrand.
122
131
  */
123
- function integrate(f, edges, relTol) {
132
+ function integrate(f, edges, relTol, noise = 4 * EPS) {
124
133
  let pieces = [];
125
134
  for (let i = 0; i + 1 < edges.length; i++) {
126
- const p = new CCPiece(f, edges[i], edges[i + 1]);
135
+ const p = new CCPiece(f, edges[i], edges[i + 1], noise);
127
136
  p.advance(16);
128
137
  pieces.push(p);
129
138
  }
@@ -133,9 +142,10 @@ function integrate(f, edges, relTol) {
133
142
  total += p.integral;
134
143
  const tol = (relTol * Math.abs(total)) / pieces.length;
135
144
  let done = true;
145
+ let count = pieces.length;
136
146
  const next = [];
137
147
  for (const p of pieces) {
138
- if (p.error <= tol || p.error <= 4 * EPS * Math.abs(p.integral)) {
148
+ if (p.error <= tol || p.error <= noise * Math.abs(p.integral)) {
139
149
  next.push(p);
140
150
  continue;
141
151
  }
@@ -144,9 +154,13 @@ function integrate(f, edges, relTol) {
144
154
  p.advance(2 * p.N);
145
155
  next.push(p);
146
156
  }
157
+ else if (count >= MAX_PIECES) {
158
+ next.push(p);
159
+ }
147
160
  else {
148
- const l = new CCPiece(f, p.a, p.c);
149
- const r = new CCPiece(f, p.c, p.b);
161
+ count++;
162
+ const l = new CCPiece(f, p.a, p.c, noise);
163
+ const r = new CCPiece(f, p.c, p.b, noise);
150
164
  l.advance(16);
151
165
  r.advance(16);
152
166
  next.push(l, r);
@@ -408,7 +422,8 @@ function logPeakIntegrate(lf, lo, hi) {
408
422
  const left = end(-1);
409
423
  const right = end(1);
410
424
  const pts = [...new Set([left, top, right])].sort((x, y) => x - y);
411
- return M + Math.log(integrate((x) => Math.exp(lf(x) - M), pts, INNER_TOL));
425
+ // lf is a sum of terms of its own size, so its values carry an absolute error of a few ε |M|
426
+ return M + Math.log(integrate((x) => Math.exp(lf(x) - M), pts, INNER_TOL, 4 * EPS * Math.max(1, Math.abs(M))));
412
427
  }
413
428
  // ---- Inner integral: the range distribution function W(w) and its complement ----
414
429
  // The integrand vanishes as φ(z) outside z. W uses [-10, 10]; 1 - W uses [-10, w + 10], which contains the peak at z ≈ w/2
@@ -486,6 +501,11 @@ function logIntegrate(lf, edges) {
486
501
  M = Math.max(M, lf(0.5 * (edges[i] + edges[i + 1])));
487
502
  if (M === -Infinity)
488
503
  return -Infinity;
504
+ // When the rounding of lf (ε |M|) exceeds 1, exp(lf - M) is noise, and the log of the integral (the log of the peak
505
+ // width, a few dozen at most) is below the rounding of M anyway (huge df with large q: ptukey(2.3e11, 2, 4.8e27,
506
+ // { lowerTail: false, logP: true }) is about -1.3e22)
507
+ if (EPS * Math.abs(M) > 1)
508
+ return M;
489
509
  for (let it = 0; it < 4; it++) {
490
510
  let seen = M;
491
511
  const v = integrate((x) => {
@@ -493,7 +513,9 @@ function logIntegrate(lf, edges) {
493
513
  if (l > seen)
494
514
  seen = l;
495
515
  return Math.exp(l - M);
496
- }, edges, REL_TOL);
516
+ }, edges, REL_TOL,
517
+ // The absolute error of lf (the inner log integral included) is a few ε |M|
518
+ 8 * EPS * Math.max(1, Math.abs(M)));
497
519
  if (Number.isFinite(v) && seen - M < 300)
498
520
  return M + Math.log(v);
499
521
  M = seen;
@@ -656,10 +678,16 @@ function rangeMaxCdf(w, k, r, upper) {
656
678
  return r === 1 ? Wc : -Math.expm1(r * Math.log1p(-Wc));
657
679
  return 1 - Math.min(rangeCdfFast(w, k), 1) ** r;
658
680
  }
681
+ /**
682
+ * log G(w) (log(1 - G(w)) if upper). From the interpolants where they apply, and integrating directly only where 1 - W
683
+ * underflows: the outer log integral evaluates this at a few hundred w, and a direct inner integral at each made
684
+ * ptukey(1e-20, 200, 5) and ptukey(2.5e118, 4, 3, { nranges: 2 }) take minutes.
685
+ */
659
686
  function logRangeMaxCdf(w, k, r, upper) {
660
687
  if (!upper)
661
- return r * logRangeCdf(w, k);
662
- const lWc = logRangeCdfC(w, k);
688
+ return r * (Math.log(w) < X_HI_W ? logRangeCdfFast(w, k) : Math.log1p(-Math.min(rangeCdfCFast(w, k), 1)));
689
+ const Wc = Math.min(rangeCdfCFast(w, k), 1);
690
+ const lWc = Wc > 1e-290 ? Math.log(Wc) : logRangeCdfC(w, k);
663
691
  if (r === 1)
664
692
  return lWc;
665
693
  // 1 - (1 - Wc)^r
@@ -671,29 +699,28 @@ function logRangeMaxCdf(w, k, r, upper) {
671
699
  * Integrate over u, the log of t = df s^2 / 2 ~ Gamma(a = df/2): ∫ a dpois(a; e^u) G(q sqrt(e^u / a)) du
672
700
  */
673
701
  function tukeyIntegral(q, k, df, r, upper) {
674
- if (df === Infinity)
702
+ if (df === Infinity || dfIsInfinite(q, k, df, r))
675
703
  return rangeMaxCdf(q, k, r, upper);
676
704
  const a = df / 2;
677
- const la = Math.log(a);
678
- const dens = gammaDensityAt(a);
705
+ const logDens = logGammaDensityAt(a);
679
706
  // Integrate over v = u - log a. For large df the peak width 1/√a is small relative to |u|, and rounding of the
680
707
  // u nodes (ulp(log a)) becomes noise in the integrand (1e-14 relative at df = 1e5). v is near 0, so rounding is small
681
708
  const f = (v) => {
682
- const { d, s } = dens(v);
683
- return d === 0 ? 0 : d * rangeMaxCdf(q * s, k, r, upper);
709
+ const d = Math.exp(logDens(v));
710
+ return d === 0 ? 0 : d * rangeMaxCdf(q * Math.exp(0.5 * v), k, r, upper);
684
711
  };
685
- return integrate(f, outerEdges(q, k, df, r, upper).map((u) => u - la), REL_TOL);
712
+ return integrate(f, outerEdges(q, k, df, r, upper), REL_TOL);
686
713
  }
687
714
  /**
688
- * Density of Gamma(a) at v = log(t/a), t f(t) = a dpois(a; t), and s = sqrt(t/a).
689
- * Loader's form a exp(-stirlerr(a) - bd0(a, t)) / sqrt(2π a), with bd0(a, t) = a (e^v - 1 - v) and s = e^(v/2)
690
- * computed directly from v (e^v - 1 - v by series for |v| < 1/2). Rounding t = a e^v before forming the density
691
- * would, for large df where the slope of the density in t (a - t) is large, turn the rounding into noise in the
692
- * integrand and disturb convergence (1e-14 relative at df = 1e5). The absolute error of the exponent is about ε × bd0.
715
+ * log density of Gamma(a) at v = log(t/a), i.e. log(t f(t)) = log(a dpois(a; t)); then s = sqrt(t/a) = e^(v/2).
716
+ * Loader's form a exp(-stirlerr(a) - bd0(a, t)) / sqrt(2π a), with bd0(a, t) = a (e^v - 1 - v) computed directly
717
+ * from v (e^v - 1 - v by series for |v| < 1/2). Rounding t = a e^v before forming the density would, for large df
718
+ * where the slope of the density in t (a - t) is large, turn the rounding into noise in the integrand and disturb
719
+ * convergence (1e-14 relative at df = 1e5; for df above about 1e30 the whole peak lies within one ulp of log a).
720
+ * The absolute error of the exponent is about ε × bd0.
693
721
  */
694
- function gammaDensityAt(a) {
695
- const st = stirlerr(a);
696
- const c0 = Math.sqrt(a / (2 * Math.PI));
722
+ function logGammaDensityAt(a) {
723
+ const c = 0.5 * Math.log(a / (2 * Math.PI)) - stirlerr(a);
697
724
  return (v) => {
698
725
  let phi;
699
726
  if (Math.abs(v) < 0.5) {
@@ -709,26 +736,30 @@ function gammaDensityAt(a) {
709
736
  else {
710
737
  phi = Math.expm1(v) - v;
711
738
  }
712
- return { d: c0 * Math.exp(-st - a * phi), s: Math.exp(0.5 * v) };
739
+ return c - a * phi;
713
740
  };
714
741
  }
742
+ /**
743
+ * Whether df is large enough that P equals its df = ∞ value to double precision. With log s ~ N(0, 1/(2a)) the
744
+ * relative change of E[G(q s)] from G(q) is about L^2 / (8a), L = d log G / d log q, which is at most about
745
+ * (k-1) r in the lower tail and q^2 in the upper
746
+ */
747
+ function dfIsInfinite(q, k, df, r) {
748
+ const L = Math.max((k - 1) * r, q * q, 1);
749
+ return L * L < 1e-17 * df;
750
+ }
715
751
  function logTukeyIntegral(q, k, df, r, upper) {
716
- if (df === Infinity)
752
+ if (df === Infinity || dfIsInfinite(q, k, df, r))
717
753
  return logRangeMaxCdf(q, k, r, upper);
718
- const a = df / 2;
719
- const la = Math.log(a);
720
- const lga1 = lgamma(a + 1);
754
+ const logDens = logGammaDensityAt(df / 2);
755
+ const lq = Math.log(q);
721
756
  // Stay on the log scale so that the deep upper tail (extremely large q), where t = e^u underflows, can be computed
722
- const lf = (u) => {
723
- const t = Math.exp(u);
724
- const ld = t > 1e-300 ? dpoisRaw(a, t, true) : a * u - t - lga1;
725
- return la + ld + logRangeMaxCdf(Math.exp(Math.log(q) + 0.5 * (u - la)), k, r, upper);
726
- };
757
+ const lf = (v) => logDens(v) + logRangeMaxCdf(Math.exp(lq + 0.5 * v), k, r, upper);
727
758
  return logIntegrate(lf, outerEdges(q, k, df, r, upper, true));
728
759
  }
729
760
  /**
730
- * Endpoints of the intervals for the outer integral (u = log t).
731
- * The Gamma(a) density concentrates around u = log a with width 1/√a; the left tail decays like t^a and the right
761
+ * Endpoints of the intervals for the outer integral, in v = log(t / a).
762
+ * The Gamma(a) density concentrates around v = 0 with width 1/√a; the left tail decays like t^a and the right
732
763
  * like e^-t. Multiplying by G(q s) moves the peak: in the lower tail G ≈ (q s)^((k-1) r) as q s → 0, which moves it
733
764
  * toward larger t (equivalent to the exponent growing from a to a + (k-1) r / 2); in the upper tail
734
765
  * 1 - G ≈ exp(-(q s)^2 / 4), equivalent to the rate growing to 1 + q^2 / (4a), so the peak moves to
@@ -739,29 +770,30 @@ function outerEdges(q, k, df, r, upper, deep = false) {
739
770
  const a = df / 2;
740
771
  // Peak of Gamma(a) before multiplying by G, and the peak it moves to when G matters in the tail (shape, center)
741
772
  let shape = a;
742
- let center = Math.log(a);
773
+ let center;
743
774
  if (upper) {
744
775
  const lq2 = 2 * Math.log(q) - Math.log(4 * a);
745
- center -= lq2 > 30 ? lq2 : Math.log1p(Math.exp(lq2));
776
+ center = -(lq2 > 30 ? lq2 : Math.log1p(Math.exp(lq2)));
746
777
  }
747
778
  else {
748
779
  shape = a + ((k - 1) * r) / 2;
749
- center = Math.log(shape);
780
+ center = Math.log1p(((k - 1) * r) / (2 * a));
750
781
  }
751
782
  // Where the density is about 1e-18 of the peak (decaying like t^shape on the left and e^-t on the right)
752
783
  const range = (c, sh) => [
753
784
  c - 9 / Math.sqrt(sh) - 41 / sh,
754
785
  c + 9 / Math.sqrt(sh) + Math.log1p(41 / sh),
755
786
  ];
756
- const [lo1, hi1] = range(Math.log(a), a);
787
+ const [lo1, hi1] = range(0, a);
757
788
  const [lo2, hi2] = range(center, shape);
758
- // The linear version is limited to where e^u does not underflow (beyond that the result is below 1e-290 and is recomputed with the log version)
759
- const lo = deep ? Math.min(lo1, lo2) : Math.max(Math.min(lo1, lo2), -740);
789
+ // The linear version is limited to where t = e^u does not underflow (beyond that the result is below 1e-290 and is
790
+ // recomputed with the log version)
791
+ const lo = deep ? Math.min(lo1, lo2) : Math.max(Math.min(lo1, lo2), -740 - Math.log(a));
760
792
  const hi = Math.max(hi1, hi2);
761
793
  // Split into a central interval containing both peaks (±4 sd) and left and right tail intervals
762
794
  const sd1 = 1 / Math.sqrt(a);
763
795
  const sd2 = 1 / Math.sqrt(shape);
764
- const edges = [lo, Math.min(Math.log(a) - 4 * sd1, center - 4 * sd2), Math.max(Math.log(a) + 4 * sd1, center + 4 * sd2), hi];
796
+ const edges = [lo, Math.min(-4 * sd1, center - 4 * sd2), Math.max(4 * sd1, center + 4 * sd2), hi];
765
797
  return [...new Set(edges.map((x) => Math.min(Math.max(x, lo), hi)))].sort((x, y) => x - y);
766
798
  }
767
799
  // ---- Public functions ----
@@ -867,12 +899,24 @@ function solveMonotone(g, y0, increasing) {
867
899
  let step = 0.05;
868
900
  let b = a + dir * step;
869
901
  let fb = g(b);
902
+ // A point past the range of doubles (e^y underflows to 0 or overflows), where g is not finite. Once one is found,
903
+ // steps go halfway to it instead of past it; a zero beyond the doubles ends at the last finite point
904
+ let bad = NaN;
870
905
  for (let i = 0; i < 200 && Math.sign(fb) === Math.sign(fa) && fb !== 0; i++) {
906
+ if (Math.abs(bad - b) < 1e-3)
907
+ return b;
871
908
  a = b;
872
909
  fa = fb;
873
910
  step *= 2;
874
- b = a + dir * step;
911
+ b = (a + dir * step - bad) * dir >= 0 ? 0.5 * (a + bad) : a + dir * step;
875
912
  fb = g(b);
913
+ while (!Number.isFinite(fb)) {
914
+ bad = b;
915
+ if (Math.abs(bad - a) < 1e-3)
916
+ return a;
917
+ b = 0.5 * (a + bad);
918
+ fb = g(b);
919
+ }
876
920
  }
877
921
  if (fb === 0)
878
922
  return b;
@@ -31,6 +31,8 @@ export function punif1(q, min, max, lowerTail, logP) {
31
31
  const h = halfIfOverflow(min, max);
32
32
  const w = max * h - min * h;
33
33
  const v = lowerTail ? (q * h - min * h) / w : (max * h - q * h) / w;
34
+ // log(v) even near probability 1, where log1p(-(other tail)) would keep more digits: R does the same
35
+ // (punif(1e-300, lower.tail = FALSE, log.p = TRUE) is 0 there)
34
36
  return logP ? Math.log(v) : v;
35
37
  }
36
38
  export function qunif1(p, min, max, lowerTail, logP) {
@@ -45,15 +47,16 @@ export function qunif1(p, min, max, lowerTail, logP) {
45
47
  return min;
46
48
  if (b !== undefined)
47
49
  return b;
48
- // Convert to a lower probability, then min + q (max - min)
49
- let q;
50
- if (logP)
51
- q = lowerTail ? Math.exp(p) : -Math.expm1(p);
52
- else
53
- q = lowerTail ? p : 0.5 - p + 0.5;
54
- if (halfIfOverflow(min, max) !== 1)
55
- return (1 - q) * min + q * max;
56
- return min + q * (max - min);
50
+ // Lower tail: min + p (max - min). Upper tail with p < 1/2: max - p (max - min), which keeps the digits of a small p
51
+ // (1 - p would lose them); otherwise min + (1 - p)(max - min) with 1 - p exact (or -expm1(log p)), as R gives
52
+ const half = halfIfOverflow(min, max) !== 1;
53
+ const at = (q) => (half ? (1 - q) * min + q * max : min + q * (max - min));
54
+ const pp = logP ? Math.exp(p) : p;
55
+ if (lowerTail)
56
+ return at(pp);
57
+ if (pp < 0.5)
58
+ return half ? pp * min + (1 - pp) * max : max - pp * (max - min);
59
+ return at(logP ? -Math.expm1(p) : 0.5 - p + 0.5);
57
60
  }
58
61
  /**
59
62
  * Density of the uniform distribution. Equivalent to R's `dunif(x, min = 0, max = 1, log = FALSE)`.
@@ -13,9 +13,28 @@ import { ddLog, ddMulNum, ddSub } from "../special/dd.js";
13
13
  function cpow(a, b) {
14
14
  return a === 1 ? 1 : Math.pow(a, b);
15
15
  }
16
- /** log u (u = x / scale) in double-double. x > 0, finite parameters */
16
+ const MIN_NORMAL = 2 ** -1022;
17
+ /**
18
+ * log u (u = x / scale) in double-double. x > 0, finite parameters. When x / scale is subnormal, 0 or overflows,
19
+ * log x - log scale instead; also for x above 1e300, where the exact remainder in standardizeDD overflows
20
+ */
17
21
  function logU(x, scale) {
18
- return ddLog(scale === 1 ? [x, 0] : standardizeDD(x, 0, scale));
22
+ if (scale === 1)
23
+ return ddLog([x, 0]);
24
+ const u = x / scale;
25
+ if (u >= MIN_NORMAL && u < Infinity && x < 1e300)
26
+ return ddLog(standardizeDD(x, 0, scale));
27
+ return ddSub(ddLog([x, 0]), ddLog([scale, 0]));
28
+ }
29
+ /** a s in double-double; only the double product when s is beyond the range of Veltkamp splitting or it overflows */
30
+ function mulLarge(a, s) {
31
+ const p = a[0] * s;
32
+ return s < 1e300 && Number.isFinite(p) ? ddMulNum(a, s) : [p, 0];
33
+ }
34
+ /** log(a / b) for positive finite a, b, also when a / b over- or underflows */
35
+ function logRatio(a, b) {
36
+ const r = a / b;
37
+ return r >= MIN_NORMAL && r < Infinity ? Math.log(r) : Math.log(a) - Math.log(b);
19
38
  }
20
39
  function allFinite(...v) {
21
40
  return v.every(Number.isFinite);
@@ -41,14 +60,21 @@ export function dweibull1(x, shape, scale, log) {
41
60
  return log ? -Math.log(scale) : 1 / scale;
42
61
  }
43
62
  const lu = logU(x, scale);
44
- const t = ddExp(ddMulNum(lu, shape));
63
+ const t = ddExp(mulLarge(lu, shape));
45
64
  if (t[0] === Infinity)
46
65
  return d0(log);
47
66
  // E = (shape - 1) log u - t
48
- const e = ddSub(shape === 1 ? [0, 0] : ddMulNum(lu, shape - 1), t);
67
+ const e = ddSub(shape === 1 ? [0, 0] : mulLarge(lu, shape - 1), t);
68
+ const r = shape / scale;
49
69
  if (log)
50
- return Math.log(shape / scale) + e[0] + e[1];
51
- return (shape / scale) * Math.exp(e[0]) * (1 + e[1]);
70
+ return logRatio(shape, scale) + e[0] + e[1];
71
+ // |log(shape / scale)| < 1455, so the density underflows; for a huge shape e[1] can exceed 1 and flip the sign below
72
+ if (e[0] < -2500)
73
+ return 0;
74
+ if (r >= MIN_NORMAL && r < Infinity && e[0] > -708)
75
+ return r * Math.exp(e[0]) * (1 + e[1]);
76
+ // shape / scale over- or underflows, or exp(E) is subnormal: fold it into the exponent
77
+ return Math.exp(logRatio(shape, scale) + e[0]) * (1 + e[1]);
52
78
  }
53
79
  export function pweibull1(q, shape, scale, lowerTail, logP) {
54
80
  if (Number.isNaN(q) || Number.isNaN(shape) || Number.isNaN(scale))
@@ -64,7 +90,12 @@ export function pweibull1(q, shape, scale, lowerTail, logP) {
64
90
  return NaN;
65
91
  }
66
92
  else {
67
- t = ddExp(ddMulNum(logU(q, scale), shape));
93
+ const l = mulLarge(logU(q, scale), shape);
94
+ t = ddExp(l);
95
+ // log(1 - exp(-t)) = log t - t / 2 + ...: below e^-700 it is log t, which stays exact where t is subnormal. Where
96
+ // t underflows to 0 the result is -Infinity, as in R (pweibull(1e-5, 1000, log.p = TRUE) is -Inf)
97
+ if (lowerTail && logP && l[0] < -700)
98
+ return t[0] === 0 ? -Infinity : l[0] + l[1];
68
99
  }
69
100
  if (!lowerTail)
70
101
  return logP ? -t[0] - t[1] : expNeg(t);
@@ -85,7 +116,11 @@ export function qweibull1(p, shape, scale, lowerTail, logP) {
85
116
  lu = lowerTail ? log1mExp(p) : p;
86
117
  else
87
118
  lu = lowerTail ? Math.log1p(-p) : Math.log(p);
88
- return scale * cpow(-lu, 1 / shape);
119
+ const v = cpow(-lu, 1 / shape);
120
+ if ((v >= MIN_NORMAL && v < Infinity) || !allFinite(shape, scale) || v === 1)
121
+ return scale * v;
122
+ // (-lu)^(1 / shape) is subnormal, 0 or overflows although scale times it may not be: in logs
123
+ return Math.exp(Math.log(scale) + Math.log(-lu) / shape);
89
124
  }
90
125
  /**
91
126
  * Density of the Weibull distribution. Equivalent to R's `dweibull(x, shape, scale = 1, log = FALSE)`.