@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
@@ -9,28 +9,80 @@ import { vectorize } from "../internal/vectorize.js";
9
9
  import { d0, dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
10
10
  import { invertContinuous } from "../internal/invert.js";
11
11
  import { lbeta } from "../special/beta.js";
12
- import { betaInc, betaIncBoth, betaIncBothDD, betaIncDD } from "../special/incbet.js";
12
+ import { SMALL_SHAPE, smallShapeG } from "../special/incbetPrefactor.js";
13
+ import { betaInc, betaIncBoth, betaIncBothDD, betaIncDD, betaIncTinyX } from "../special/incbet.js";
13
14
  import { dbinomRawDD } from "../special/loader.js";
14
- import { ddAdd, ddDiv, twoProd } from "../special/dd.js";
15
+ import { ddAdd, ddDiv, ddLog, ddMul, ddNeg, ddSub, twoProd, twoSum } from "../special/dd.js";
15
16
  import { dgamma1, pgamma1, qgamma1 } from "./gamma.js";
16
17
  import { dnf1, pnf1, qnf1 } from "./nbeta.js";
17
18
  import { betaQuantileGuess } from "./beta.js";
19
+ const LOG_DBL_MIN = Math.log(2.2250738585072014e-308);
20
+ /**
21
+ * Log density in double-double from log p and log q (p = m x/(n + m x), q = 1 - p = n/(n + m x)), with a = m/2, b = n/2:
22
+ * f(x) = (m/n) p^(a-1) q^(b+1) / B(a, b) (the beta density of p times dp/dx = (m/n) q^2)
23
+ * log(1/B(a, b)) for a small shape from 1/B(a, b) = ab/(a + b) Γ(1+a+b)/(Γ(1+a) Γ(1+b)) (incbetPrefactor.ts)
24
+ */
25
+ function fLogDensity(m, n, lp, lq) {
26
+ const a = m / 2;
27
+ const b = n / 2;
28
+ const s = Math.min(a, b);
29
+ const lib = s < SMALL_SHAPE ? ddAdd([Math.log(s) - Math.log1p(s / Math.max(a, b)), 0], smallShapeG(a, b)) : [-lbeta(a, b), 0];
30
+ // (a - 1 and b + 1 exactly, in double-double: their rounding times log p of -700 was 3e-14 of the density)
31
+ return ddAdd(ddAdd(ddAdd(ddSub(ddLog([m, 0]), ddLog([n, 0])), ddMul(lp, twoSum(a, -1))), ddMul(lq, twoSum(b, 1))), lib);
32
+ }
33
+ function fromLog(e, log) {
34
+ return log ? e[0] + e[1] : Math.exp(e[0]) * (1 + e[1]);
35
+ }
36
+ /**
37
+ * p = m x/(n + m x) and q = n/(n + m x) in double-double, or undefined where m x is huge (from 1e290; the callers then
38
+ * form q ≈ n/(m x) directly). Rounding in p and q would be amplified m/2 and n/2 times respectively (5e-13 relative at
39
+ * df1 = 1e6). Where m x is below 1e-290 the double-double product loses its low part or underflows (pf(1.29e-232,
40
+ * 1.78e-123, 2.18e-48) was 0 although pf at 2.6e-269 was 1), so m x and n are first scaled by 2^600 (exactly; the
41
+ * smaller of m and x is below 1e-145 there, and n below 1e127, so that n 2^600 stays finite; for a larger n, p is below
42
+ * DBL_MIN and the callers work from its log)
43
+ */
44
+ function fRatios(x, m, n) {
45
+ // A factor above 1e290 is scaled down by 2^600 and the other up (exactly), as its splitting in twoProd overflows: at a
46
+ // subnormal df1 and x from 1e301, m x is moderate but was taken for huge, and n/m overflowed in the callers' q ≈ n/(m x)
47
+ // (pf(1e301, 1.4e-312, 6.72, { lowerTail: false }) was 1, 1.77e-311 expected; qf there did not return)
48
+ const S = 2 ** 600;
49
+ let mx = x > 1e290 ? twoProd(m * S, x / S) : m > 1e290 ? twoProd(m / S, x * S) : twoProd(m, x);
50
+ if (!(Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290))
51
+ return undefined;
52
+ let nn = n;
53
+ if (x > 0 && mx[0] < 1e-290 && n < 1e127) {
54
+ mx = m < x ? twoProd(m * S, x) : twoProd(m, x * S);
55
+ nn = n * S;
56
+ }
57
+ const d = ddAdd(mx, [nn, 0]);
58
+ return [ddDiv(mx, d), ddDiv([nn, 0], d)];
59
+ }
18
60
  function fDensity(x, m, n, log) {
19
- // p = m x/(n + m x) and q = n/(n + m x) are formed in double-double. Rounding in p and q would be
20
- // amplified m/2 and n/2 times respectively (5e-13 relative at df1 = 1e6)
21
- const mx = twoProd(m, x);
61
+ // p or q below DBL_MIN (m x/n beyond e^±708): the ratios themselves would be subnormal or underflow (the density was
62
+ // NaN, as R's is: df(1.33e-322, 1.04, 206159)). The tiny one is r/(1 + r) or 1/(1 + r), r = m x/n, whose log is
63
+ // -|log r| to within DBL_MIN; the other is 1 to within DBL_MIN
64
+ if (x > 0 && x < Infinity && Math.abs(Math.log(m) + Math.log(x) - Math.log(n)) > 700) {
65
+ const lr = ddAdd(ddSub(ddLog([m, 0]), ddLog([n, 0])), ddLog([x, 0]));
66
+ if (lr[0] < LOG_DBL_MIN)
67
+ return fromLog(fLogDensity(m, n, lr, [-Math.exp(lr[0]), 0]), log);
68
+ if (-lr[0] < LOG_DBL_MIN)
69
+ return fromLog(fLogDensity(m, n, [-Math.exp(-lr[0]), 0], ddNeg(lr)), log);
70
+ }
71
+ const r = fRatios(x, m, n);
22
72
  let pd;
23
73
  let qd;
24
- if (Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290) {
25
- const d = ddAdd(mx, [n, 0]);
26
- pd = ddDiv(mx, d);
27
- qd = ddDiv([n, 0], d);
74
+ if (r !== undefined) {
75
+ [pd, qd] = r;
28
76
  }
29
77
  else {
30
78
  // m x is huge (the double-double product overflows): p ≈ 1, q ≈ n/(m x) in double precision
31
79
  qd = [n / m / x, 0];
32
80
  pd = [1, -qd[0]];
33
81
  }
82
+ // A small df: Loader's form loses about ε |log(df/2)| / 2 in its exponent (incbetPrefactor.ts), and the factor m^2 n
83
+ // below underflowed (df(6.6e-112, 3.2e-173, 1868) was -Infinity on the log scale, NaN at x = 4.6e-157)
84
+ if (Math.min(m, n) / 2 < SMALL_SHAPE)
85
+ return fromLog(fLogDensity(m, n, ddLog(pd), ddLog(qd)), log);
34
86
  const p = pd[0];
35
87
  const q = qd[0];
36
88
  if (m >= 2) {
@@ -62,6 +114,7 @@ export function dfDensity1(x, m, n, log) {
62
114
  return dgamma1(x, m / 2, 2 / m, log); // χ²_m / m
63
115
  if (!Number.isFinite(m)) {
64
116
  // n / χ²_n: 1/x follows a gamma distribution with shape n/2, scale 2/n
117
+ // At tiny x this is 0 / 0 = NaN (x^2 underflows), as R gives (df(1e-300, Inf, 5) is NaN); the log is finite
65
118
  const dens = dgamma1(1 / x, n / 2, 2 / n, log);
66
119
  return log ? dens - 2 * Math.log(x) : dens / (x * x);
67
120
  }
@@ -69,14 +122,36 @@ export function dfDensity1(x, m, n, log) {
69
122
  return m < 2 ? NaN : d0(log); // R gives NaN at x = Inf when df1 < 2
70
123
  return fDensity(x, m, n, log);
71
124
  }
72
- /** P[F <= x] (lower) / P[F > x] (!lower). x finite and positive, m, n finite */
125
+ /**
126
+ * [log, linear] of P[F <= x] (lower) / P[F > x] where m x/(n + m x) or n/(n + m x) is below DBL_MIN, from the log of
127
+ * that ratio (betaIncTinyX); undefined elsewhere. With r = m x/n the ratios are r/(1 + r) and 1/(1 + r), so the log of
128
+ * the smaller one is -|log r| to within DBL_MIN. Forming the ratio itself would round it in the subnormal range
129
+ * (pf(5.43e-319, 1.04, 206159) was off by 4.5e-14) or underflow it to 0 (pf(1e300, 0.169, 1.18e-86, { lowerTail: false })
130
+ * was 0, about 1 expected)
131
+ */
132
+ function pfTiny(x, m, n, lower, wantLog) {
133
+ // (a cheap filter first: the double-double logarithms are only needed out there)
134
+ // (x = 0 and Infinity, which the quantile search reaches, are left to the ratios below)
135
+ if (!(x > 0 && x < Infinity) || Math.abs(Math.log(m) + Math.log(x) - Math.log(n)) < 700)
136
+ return undefined;
137
+ const lr = ddSub(ddAdd(ddLog([m, 0]), ddLog([x, 0])), ddLog([n, 0]));
138
+ if (lr[0] < LOG_DBL_MIN)
139
+ return betaIncTinyX(m / 2, n / 2, Math.exp(lr[0]), lr, lower, wantLog);
140
+ if (-lr[0] < LOG_DBL_MIN)
141
+ return betaIncTinyX(n / 2, m / 2, Math.exp(-lr[0]), ddNeg(lr), !lower, wantLog);
142
+ return undefined;
143
+ }
144
+ /** P[F <= x] (lower) / P[F > x] (!lower). x positive, m, n finite */
73
145
  function pfRaw(x, m, n, lower, log) {
146
+ if (x === Infinity)
147
+ return lower === log ? 0 : lower ? 1 : -Infinity;
148
+ const t = pfTiny(x, m, n, lower, log);
149
+ if (t !== undefined)
150
+ return log ? t[0] : t[1];
74
151
  // Form m x/(n + m x) and n/(n + m x) in double-double (rounding would be amplified m/2 and n/2 times)
75
- const mx = twoProd(m, x);
76
- if (Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290) {
77
- const d = ddAdd(mx, [n, 0]);
78
- return betaIncDD(m / 2, n / 2, ddDiv(mx, d), ddDiv([n, 0], d), lower, log);
79
- }
152
+ const r = fRatios(x, m, n);
153
+ if (r !== undefined)
154
+ return betaIncDD(m / 2, n / 2, r[0], r[1], lower, log);
80
155
  // m x is huge: form 1 - z = n/(n + m x) ≈ (n/m)/x directly
81
156
  const zc = n / m / x;
82
157
  return betaInc(m / 2, n / 2, 1 - zc, zc, lower, log);
@@ -91,14 +166,39 @@ function fQuantileGuess(m, n, lower, logTarget) {
91
166
  }
92
167
  /** [log, linear] of pfRaw (each value identical to pfRaw) */
93
168
  function pfRawBoth(x, m, n, lower) {
94
- const mx = twoProd(m, x);
95
- if (Number.isFinite(mx[0]) && Number.isFinite(mx[1]) && Math.abs(mx[0]) < 1e290) {
96
- const d = ddAdd(mx, [n, 0]);
97
- return betaIncBothDD(m / 2, n / 2, ddDiv(mx, d), ddDiv([n, 0], d), lower);
98
- }
169
+ // (x = Infinity, which the quantile search reaches from a far step, was NaN, and the search spent its iterations on it
170
+ // at 25 ms each: qf(-735.2, 1.25e-305, 3.3e5, { lowerTail: false, logP: true }) returned 1 after 5 s)
171
+ if (x === Infinity)
172
+ return lower ? [0, 1] : [-Infinity, 0];
173
+ const t = pfTiny(x, m, n, lower, true);
174
+ if (t !== undefined)
175
+ return t;
176
+ const r = fRatios(x, m, n);
177
+ if (r !== undefined)
178
+ return betaIncBothDD(m / 2, n / 2, r[0], r[1], lower);
99
179
  const zc = n / m / x;
100
180
  return betaIncBoth(m / 2, n / 2, 1 - zc, zc, lower);
101
181
  }
182
+ const MIN_NORMAL = 2.2250738585072014e-308;
183
+ /**
184
+ * P[χ²_m / m <= q] (lower), the F distribution with df2 = Inf: pgamma at q m, or with scale 2/m where q m is below the
185
+ * normal range (the product had lost its digits or underflowed to 0: pf(2e-323, 0.012, Inf) was 0, as R 4.5.2 gives,
186
+ * where it is 0.011; so the quantile 0 of qf(7.8e-37, 0.012, Inf) did not round-trip). Not for a subnormal m, where 2/m
187
+ * overflows
188
+ */
189
+ function pChisqLimit(q, m, lowerTail, logP) {
190
+ const t = q * m;
191
+ if (t < MIN_NORMAL && m > MIN_NORMAL)
192
+ return pgamma1(q, m / 2, 2 / m, lowerTail, logP);
193
+ return pgamma1(t, m / 2, 2, lowerTail, logP);
194
+ }
195
+ /** The quantile of χ²_m / m, likewise with scale 2/m where the quantile or that of χ²_m is below the normal range */
196
+ function qChisqLimit(p, m, lowerTail, logP) {
197
+ const t = qgamma1(p, m / 2, 2, lowerTail, logP);
198
+ if ((t < MIN_NORMAL || t / m < MIN_NORMAL) && m > MIN_NORMAL)
199
+ return qgamma1(p, m / 2, 2 / m, lowerTail, logP);
200
+ return t / m;
201
+ }
102
202
  export function pf1(q, m, n, lowerTail, logP) {
103
203
  if (Number.isNaN(q) || Number.isNaN(m) || Number.isNaN(n))
104
204
  return NaN;
@@ -115,7 +215,7 @@ export function pf1(q, m, n, lowerTail, logP) {
115
215
  return q < 1 ? dt0(lowerTail, logP) : dt1(lowerTail, logP);
116
216
  }
117
217
  if (!Number.isFinite(n))
118
- return pgamma1(q * m, m / 2, 2, lowerTail, logP); // χ²_m
218
+ return pChisqLimit(q, m, lowerTail, logP); // χ²_m
119
219
  if (!Number.isFinite(m))
120
220
  return pgamma1(n / q, n / 2, 2, !lowerTail, logP); // n / χ²_n
121
221
  return pfRaw(q, m, n, lowerTail, logP);
@@ -131,16 +231,35 @@ export function qf1(p, m, n, lowerTail, logP) {
131
231
  if (!Number.isFinite(m) && !Number.isFinite(n))
132
232
  return 1;
133
233
  if (!Number.isFinite(n))
134
- return qgamma1(p, m / 2, 2, lowerTail, logP) / m;
234
+ return qChisqLimit(p, m, lowerTail, logP);
135
235
  if (!Number.isFinite(m))
136
236
  return n / qgamma1(p, n / 2, 2, !lowerTail, logP);
137
237
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
238
+ // A df2 so large that χ²_n/n is 1 on the scale of the quantile: the χ² limit, as for n = Inf. With W = χ²_n/n and G
239
+ // the distribution function of χ²_m, P[F <= x] = E G(m x W) moves from G(m x) by Var W (m x)² G''/2 = (m x)² G''/n,
240
+ // and (m x)² G''/G is of the order of (d log G/d log t)², at most (m + 2 |log p| + 1e3)² (p the smaller tail): the
241
+ // quantile moves by less than 1e-20 relative. (The incomplete beta function, out of its range at such a df (see the
242
+ // known violations), was NaN in the bulk, and the search took seconds: qf(1.9e-13, 0.0885, 6e302) did not return)
243
+ if (n > 1e20 * (m - 2 * logTarget + 1e3) ** 2)
244
+ return qChisqLimit(p, m, lowerTail, logP);
138
245
  // Near 0, P[F <= x] ≈ (m x / n)^(m/2) / ((m/2) B(m/2, n/2)). The answer is 0 if it underflows
139
246
  if (lower && (logTarget + Math.log(m / 2) + lbeta(m / 2, n / 2)) / (m / 2) + Math.log(n / m) < -746)
140
247
  return 0;
141
- // Near infinity, P[F > x] ≈ (n / (m x))^(n/2) / ((n/2) B(m/2, n/2)). Inf if it overflows
142
- if (!lower && -(logTarget + Math.log(n / 2) + lbeta(m / 2, n / 2)) / (n / 2) + Math.log(n / m) > 709.78)
248
+ // Near infinity, P[F > x] ≈ (n / (m x))^(n/2) / ((n/2) B(m/2, n/2)). Inf if it overflows, as confirmed by the upper
249
+ // tail at the largest double (the leading term alone sent qf(5.95e-155, 2875.5, 1, { lowerTail: false }) to Infinity,
250
+ // where pf(1.797e308, ...) is 5.9503e-155, below p)
251
+ if (!lower &&
252
+ -(logTarget + Math.log(n / 2) + lbeta(m / 2, n / 2)) / (n / 2) + Math.log(n / m) > 709.78 &&
253
+ pfRaw(Number.MAX_VALUE, m, n, false, true) > logTarget) {
143
254
  return Infinity;
255
+ }
256
+ // The other way round, a tiny df2 leaves the lower tail below the target up to the largest double (nearly all the
257
+ // mass lies beyond it: qf(8.8e-131, 0.754, 4.6e-152) returned 1.8e308, where pf is 2.4e-149), and a tiny df1 the
258
+ // upper tail below the target from the smallest positive number on
259
+ if (lower && n < 1 && pfRaw(Number.MAX_VALUE, m, n, true, true) < logTarget)
260
+ return Infinity;
261
+ if (!lower && m < 1 && pfRaw(Number.MIN_VALUE, m, n, false, true) < logTarget)
262
+ return 0;
144
263
  return invertContinuous({
145
264
  logTarget,
146
265
  ...(linearTarget !== undefined && { linearTarget }),
@@ -1,5 +1,6 @@
1
1
  import { type Vectorizable, type VectorResult } from "../internal/vectorize.js";
2
2
  import { type DensityOptions, type TailOptions } from "../internal/dpq.js";
3
+ import { type DD } from "../special/dd.js";
3
4
  /**
4
5
  * Parameters of the gamma distribution. Give either `rate` or `scale`; if both are given,
5
6
  * `scale` must equal `1 / rate`.
@@ -18,8 +19,18 @@ export declare function gammaScale(params: GammaParams): number;
18
19
  export declare function dgammaStdLog(x: number, shape: number): number;
19
20
  export declare function dgamma1(x: number, shape: number, scale: number, log: boolean): number;
20
21
  export declare function pgamma1(q: number, shape: number, scale: number, lowerTail: boolean, logP: boolean): number;
21
- /** Quantile of the standardized gamma distribution. 0 < p < 1 (range checks are the caller's job) */
22
- export declare function qgammaStd(p: number, shape: number, lowerTail: boolean, logP: boolean): number;
22
+ /**
23
+ * log of the standardized gamma quantile when it is below the smallest normal double (else undefined): there
24
+ * P(shape, x) = x^shape / Gamma(shape + 1) to double precision, so log x = (log P + lgamma(shape + 1)) / shape.
25
+ * lower, logTarget and linearTarget as from smallerTail. log P from the linear target in double-double where there is
26
+ * one (log P rounded would lose eps |log P| / shape relative in x)
27
+ */
28
+ export declare function logTinyGammaQuantile(logTarget: number, lower: boolean, shape: number, linearTarget: number | undefined): DD | undefined;
29
+ /**
30
+ * Quantile of the standardized gamma distribution times scale (default 1). 0 < p < 1 (range checks are the caller's
31
+ * job). Where the standardized quantile is below the smallest normal double the scaling is done in logs
32
+ */
33
+ export declare function qgammaStd(p: number, shape: number, lowerTail: boolean, logP: boolean, scale?: number): number;
23
34
  export declare function qgamma1(p: number, shape: number, scale: number, lowerTail: boolean, logP: boolean): number;
24
35
  /**
25
36
  * Density of the gamma distribution. Equivalent to R's `dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)`.
@@ -5,6 +5,9 @@
5
5
  // = dpois(shape; y) * shape / x (shape < 1)
6
6
  // The distribution function uses the incomplete gamma function (src/special/igam.ts); quantiles use Newton's
7
7
  // method (src/internal/invert.ts) from the DiDonato & Morris starting value.
8
+ // Where y = x/scale is below the smallest normal double (subnormal, or 0 although x > 0), the leading terms
9
+ // f(x) = y^shape / (Gamma(shape) x), P[X <= x] = y^shape / Gamma(shape + 1)
10
+ // are exact to double precision (the next terms are O(y) relative), and are taken in logs with log y = log x - log scale.
8
11
  import { vectorize } from "../internal/vectorize.js";
9
12
  import { d0, dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
10
13
  import { invertContinuous } from "../internal/invert.js";
@@ -12,6 +15,8 @@ import { gammaInc, gammaIncBoth } from "../special/igam.js";
12
15
  import { findInverseGamma } from "../special/igami.js";
13
16
  import { lgamma, lgamma1p } from "../special/gamma.js";
14
17
  import { dpoisRaw } from "../special/loader.js";
18
+ import { ddAdd, ddDivNum, ddLog, ddMulNum, ddSub } from "../special/dd.js";
19
+ import { ddExp, log1mExp, logRatioDD } from "../internal/ddexp.js";
15
20
  import { qnorm } from "./normal.js";
16
21
  /** Determine scale from rate / scale (as in R, giving both is an error unless scale = 1/rate; also used by rgamma) */
17
22
  export function gammaScale(params) {
@@ -24,16 +29,52 @@ export function gammaScale(params) {
24
29
  }
25
30
  if (scale !== undefined)
26
31
  return scale;
32
+ // For a rate below about 5.6e-309 (subnormal), 1 / rate overflows to Infinity and the whole distribution is treated as
33
+ // lying at +Infinity (pgamma 0 and dgamma 0 at every finite x, qgamma Infinity), as R does with its scale = 1 / rate;
34
+ // some quantiles of the exact distribution would be finite there
27
35
  if (rate !== undefined)
28
36
  return 1 / rate;
29
37
  return 1;
30
38
  }
39
+ const MIN_NORMAL = 2 ** -1022;
40
+ const EULER = 0.5772156649015329;
41
+ const LOG_MIN_NORMAL = -1022 * Math.LN2;
42
+ /** c t in double-double; only the double product where c is beyond the range of Veltkamp splitting */
43
+ const mulBig = (t, c) => (c < 1e300 ? ddMulNum(t, c) : [t[0] * c, 0]);
44
+ /** exp of a double-double; 0 below the subnormal range (where the low part could carry -0 or NaN into ddExp's result) */
45
+ const expOf = (l) => (l[0] < -746 ? 0 : ddExp(l)[0]);
46
+ /**
47
+ * log P[X <= x] where y = x / scale is below the smallest normal double (x > 0, finite scale): shape log y -
48
+ * lgamma(shape + 1), with log y from log x - log scale (y itself has lost digits in the division, or is 0)
49
+ */
50
+ function logLowerTiny(x, shape, scale) {
51
+ const m = mulBig(logRatioDD(x, scale), shape);
52
+ const lg = lgamma1p(shape);
53
+ // (both terms are negative; where one overflows the sum is -Infinity, which a double-double sum made NaN:
54
+ // pchisq(1e-320, 1e306) was NaN)
55
+ if (!Number.isFinite(m[0]) || !Number.isFinite(lg))
56
+ return [m[0] - lg, 0];
57
+ return ddAdd(m, [-lg, 0]);
58
+ }
59
+ /**
60
+ * Whether the log density l = lp + (log of a divisor) has cancelled to below half of |lp|: the roundings of the two
61
+ * logs (eps times hundreds near the ends of the range) are then large against l (dgamma(1.2e-289, 40.4,
62
+ * scale 1.5e-292, log) was 1e-13 off at -0.38)
63
+ */
64
+ const cancels = (l, lp) => Math.abs(l) < 0.5 * Math.abs(lp);
65
+ /** log(f / d) from the linear factor f where f and the quotient are normal (relative accuracy kept), else l */
66
+ function logOfLinear(f, d, l) {
67
+ if (!(f >= MIN_NORMAL && f < Infinity))
68
+ return l;
69
+ const v = f / d;
70
+ return v >= MIN_NORMAL && v < Infinity ? Math.log(v) : l;
71
+ }
31
72
  /** Log density of the standardized (scale = 1) gamma distribution. x > 0, shape > 0 */
32
73
  export function dgammaStdLog(x, shape) {
33
74
  if (shape < 1) {
34
75
  const pr = dpoisRaw(shape, x, true);
35
76
  const r = shape / x;
36
- return pr + (Number.isFinite(r) ? Math.log(r) : Math.log(shape) - Math.log(x));
77
+ return pr + (r >= MIN_NORMAL && r < Infinity ? Math.log(r) : Math.log(shape) - Math.log(x));
37
78
  }
38
79
  return dpoisRaw(shape - 1, x, true);
39
80
  }
@@ -53,22 +94,46 @@ export function dgamma1(x, shape, scale, log) {
53
94
  return d0(log);
54
95
  return log ? -Math.log(scale) : 1 / scale;
55
96
  }
97
+ if (x / scale < MIN_NORMAL && scale < Infinity && shape < Infinity) {
98
+ // log f = shape log y + log(shape) - lgamma(shape + 1) - log x (e^-y is 1)
99
+ const lp = logLowerTiny(x, shape, scale);
100
+ // (-Infinity where shape log y or lgamma(shape + 1) overflows: dgamma(3.1e-272, 4.4e307, scale 4.1e138) was NaN)
101
+ if (lp[0] === -Infinity)
102
+ return d0(log);
103
+ const l = ddAdd(ddSub(lp, ddLog([x, 0])), ddLog([shape, 0]));
104
+ return log ? l[0] + l[1] : expOf(l);
105
+ }
56
106
  if (shape < 1) {
57
107
  const pr = dpoisRaw(shape, x / scale, log);
58
108
  if (log) {
109
+ // log(shape / x), from the logs where the quotient over- or underflows or is subnormal (it has lost digits:
110
+ // dgamma(8.8e214, 7.4e-105, rate 6.3e-268, log) was off by 4e-6)
59
111
  const r = shape / x;
60
- return pr + (Number.isFinite(r) ? Math.log(r) : Math.log(shape) - Math.log(x));
112
+ const l = pr + (r >= MIN_NORMAL && r < Infinity ? Math.log(r) : Math.log(shape) - Math.log(x));
113
+ return cancels(l, pr) ? logOfLinear(dpoisRaw(shape, x / scale, false) * shape, x, l) : l;
61
114
  }
62
- return (pr * shape) / x;
115
+ const ps = pr * shape;
116
+ return ps >= MIN_NORMAL || x >= 1 ? ps / x : Math.exp(dgamma1(x, shape, scale, true));
63
117
  }
64
118
  const pr = dpoisRaw(shape - 1, x / scale, log);
65
- return log ? pr - Math.log(scale) : pr / scale;
119
+ if (log) {
120
+ const l = pr - Math.log(scale);
121
+ return cancels(l, pr) ? logOfLinear(dpoisRaw(shape - 1, x / scale, false), scale, l) : l;
122
+ }
123
+ // Where the Poisson factor (or its product with shape above) is below the normal range, a small scale or x can
124
+ // bring the density back into it with the factor's lost digits (dgamma(6.8e-291, 6.37, scale 1.6e-231) was 0.4%
125
+ // off): exp of the log density instead
126
+ return pr >= MIN_NORMAL || scale >= 1 ? pr / scale : Math.exp(dgamma1(x, shape, scale, true));
66
127
  }
67
128
  export function pgamma1(q, shape, scale, lowerTail, logP) {
68
129
  if (Number.isNaN(q) || Number.isNaN(shape) || Number.isNaN(scale))
69
130
  return NaN;
70
131
  if (shape < 0 || scale <= 0)
71
132
  return NaN;
133
+ // P[X <= Inf] = 1 also at scale = Inf (from a subnormal rate, 1/rate overflows), where q / scale is NaN. R 4.5.2
134
+ // gives NaN there (pgamma(Inf, 892.4, rate = 2.8e-316))
135
+ if (q === Infinity)
136
+ return dt1(lowerTail, logP);
72
137
  const x = q / scale;
73
138
  if (Number.isNaN(x))
74
139
  return x;
@@ -78,17 +143,57 @@ export function pgamma1(q, shape, scale, lowerTail, logP) {
78
143
  // returned for every finite x (docs/differences-from-r.md)
79
144
  if (shape === Infinity)
80
145
  return x === Infinity ? dt1(lowerTail, logP) : dt0(lowerTail, logP);
146
+ if (q <= 0)
147
+ return dt0(lowerTail, logP);
148
+ if (x < MIN_NORMAL && scale < Infinity) {
149
+ const l = logLowerTiny(q, shape, scale);
150
+ const lp = l[0] + l[1];
151
+ if (lowerTail)
152
+ return logP ? lp : expOf(l);
153
+ // 1 - P with P from the double-double log where P < 1/2 (exp of the rounded log loses eps |log P| relative)
154
+ if (lp > -1e-10 && logP) {
155
+ // log Q = log(-lp) + log1p(lp / 2) with -lp = shape (-m), m = log y - lgamma1p(shape) / shape, from log shape: Q is
156
+ // of the order of shape and lost digits where it is subnormal (pgamma(1e-310, 5e-324, upper, log) was 3e-4 off).
157
+ // lgamma1p(shape) / shape is -γ (1 + O(shape)) where lgamma1p(shape) would be subnormal
158
+ const m = logRatioDD(q, scale)[0] - (shape < 1e-300 ? -EULER : lgamma1p(shape) / shape);
159
+ return Math.log(shape) + Math.log(-m) + Math.log1p(lp / 2);
160
+ }
161
+ if (lp > -Math.LN2)
162
+ return logP ? Math.log(-Math.expm1(lp)) : -Math.expm1(lp);
163
+ const e = expOf(l);
164
+ return logP ? Math.log1p(-e) : 1 - e;
165
+ }
81
166
  if (x <= 0)
82
167
  return dt0(lowerTail, logP);
83
168
  return gammaInc(shape, x, lowerTail, logP);
84
169
  }
85
- /** Quantile of the standardized gamma distribution. 0 < p < 1 (range checks are the caller's job) */
86
- export function qgammaStd(p, shape, lowerTail, logP) {
170
+ /**
171
+ * log of the standardized gamma quantile when it is below the smallest normal double (else undefined): there
172
+ * P(shape, x) = x^shape / Gamma(shape + 1) to double precision, so log x = (log P + lgamma(shape + 1)) / shape.
173
+ * lower, logTarget and linearTarget as from smallerTail. log P from the linear target in double-double where there is
174
+ * one (log P rounded would lose eps |log P| / shape relative in x)
175
+ */
176
+ export function logTinyGammaQuantile(logTarget, lower, shape, linearTarget) {
177
+ const lp = lower ? logTarget : linearTarget !== undefined ? Math.log1p(-linearTarget) : log1mExp(logTarget);
178
+ const lg = lgamma1p(shape);
179
+ if (!(lp < shape * LOG_MIN_NORMAL - lg))
180
+ return undefined;
181
+ const s = ddAdd(lower && linearTarget !== undefined ? ddLog([linearTarget, 0]) : [lp, 0], [lg, 0]);
182
+ // (in double where the shape or the quotient is beyond the range of Veltkamp splitting; exp of it is 0 or 1 then)
183
+ const q = s[0] / shape;
184
+ return shape < 1e300 && Math.abs(q) < 1e300 ? ddDivNum(s, shape) : [q, 0];
185
+ }
186
+ /**
187
+ * Quantile of the standardized gamma distribution times scale (default 1). 0 < p < 1 (range checks are the caller's
188
+ * job). Where the standardized quantile is below the smallest normal double the scaling is done in logs
189
+ */
190
+ export function qgammaStd(p, shape, lowerTail, logP, scale = 1) {
87
191
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
88
- // If the distribution function at the smallest positive number already passes the target, the answer is too small to represent (0)
89
- const atMin = gammaInc(shape, Number.MIN_VALUE, lower, true);
90
- if (lower ? atMin >= logTarget : atMin <= logTarget)
91
- return 0;
192
+ const tiny = logTinyGammaQuantile(logTarget, lower, shape, linearTarget);
193
+ // (the log is -Infinity where log P / shape overflows at a subnormal shape; added to log scale in double-double it was
194
+ // NaN: qchisq(0.5, 1e-310) was NaN)
195
+ if (tiny !== undefined)
196
+ return expOf(scale === 1 || tiny[0] === -Infinity ? tiny : ddAdd(tiny, ddLog([scale, 0])));
92
197
  let x0;
93
198
  if (shape > 1 && logTarget <= -700) {
94
199
  // Deep tail: Wilson-Hilferty approximation x = a (1 - 1/(9a) + z / sqrt(9a))^3
@@ -111,7 +216,7 @@ export function qgammaStd(p, shape, lowerTail, logP) {
111
216
  for (let i = 0; i < 3; i++)
112
217
  x0 = -logTarget - lgamma(shape) + (shape - 1) * Math.log(x0);
113
218
  }
114
- return invertContinuous({
219
+ const x = invertContinuous({
115
220
  logTarget,
116
221
  ...(linearTarget !== undefined && { linearTarget }),
117
222
  lower,
@@ -125,6 +230,7 @@ export function qgammaStd(p, shape, lowerTail, logP) {
125
230
  hi: Infinity,
126
231
  positive: true,
127
232
  });
233
+ return x * scale;
128
234
  }
129
235
  export function qgamma1(p, shape, scale, lowerTail, logP) {
130
236
  if (Number.isNaN(p) || Number.isNaN(shape) || Number.isNaN(scale))
@@ -139,7 +245,11 @@ export function qgamma1(p, shape, scale, lowerTail, logP) {
139
245
  // Shape Inf: all the mass at +Inf, so every probability strictly between 0 and 1 maps to Inf
140
246
  if (shape === Infinity)
141
247
  return Infinity;
142
- return qgammaStd(p, shape, lowerTail, logP) * scale;
248
+ // Scale Inf (1/rate overflows for a rate below 5.6e-309): pgamma is 0 at every finite q there, so Inf likewise (the
249
+ // scaling of a quantile below the normal range made it NaN: qgamma(3.3e-160, 0.5, rate = 4.2e-319))
250
+ if (scale === Infinity)
251
+ return Infinity;
252
+ return qgammaStd(p, shape, lowerTail, logP, scale);
143
253
  }
144
254
  /**
145
255
  * Density of the gamma distribution. Equivalent to R's `dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)`.
@@ -9,13 +9,29 @@ import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
9
9
  import { log1mExp } from "../internal/ddexp.js";
10
10
  import { nonInt } from "../internal/integer.js";
11
11
  import { dbinomRawDD } from "../special/loader.js";
12
- import { twoSum } from "../special/dd.js";
12
+ import { ddLog, ddMul, ddMulNum, twoSum } from "../special/dd.js";
13
13
  /** p and q = 1 - p in double-double (the smaller one is the exact base) */
14
14
  export function probPair(prob) {
15
15
  return prob <= 0.5
16
16
  ? { pd: [prob, 0], qd: twoSum(1, -prob) }
17
17
  : { pd: twoSum(1, -(1 - prob)), qd: [1 - prob, 0] };
18
18
  }
19
+ /**
20
+ * q^n (its log if log) for an integer n >= 0 by Loader's form, except from n = 1e290 on: there its double-double
21
+ * products overflow in the splitting of n (pgeom(8.7e299, 1.1e-300) was NaN, 0.616 expected), and n log q is formed in
22
+ * double-double with n scaled down by 2^64 and log q up by 2^64 (both exact)
23
+ */
24
+ function qPow(n, pd, qd, log) {
25
+ if (n < 1e290)
26
+ return dbinomRawDD(0, n, pd, qd, log);
27
+ // log q = -p - p²/2 - ... for a tiny p (ddLog of 1 - p lost a subnormal p in its low part, and pgeom(1e290, 5e-324)
28
+ // was 0, 4.9e-34 expected)
29
+ const lq = qd[0] === 1 ? [-pd[0], -(pd[0] * pd[0]) / 2] : ddLog(qd);
30
+ const l = ddMul([n / 2 ** 64, 0], ddMulNum(lq, 2 ** 64));
31
+ if (!(l[0] > -Infinity))
32
+ return log ? -Infinity : 0;
33
+ return log ? l[0] + l[1] : Math.exp(l[0]) * (1 + l[1]);
34
+ }
19
35
  function badProb(prob) {
20
36
  return !(prob > 0) || prob > 1;
21
37
  }
@@ -29,13 +45,13 @@ export function dgeom1(x, prob, log) {
29
45
  const n = Math.round(x);
30
46
  const { pd, qd } = probPair(prob);
31
47
  // q^n
32
- const qn = dbinomRawDD(0, n, pd, qd, log);
48
+ const qn = qPow(n, pd, qd, log);
33
49
  return log ? Math.log(prob) + qn : prob * qn;
34
50
  }
35
51
  /** P[X > x] = q^(x+1) (x a nonnegative integer) */
36
52
  function upper(x, prob, log) {
37
53
  const { pd, qd } = probPair(prob);
38
- return dbinomRawDD(0, x + 1, pd, qd, log);
54
+ return qPow(x + 1, pd, qd, log);
39
55
  }
40
56
  function pgeomRaw(x, prob, lowerTail, logP) {
41
57
  if (!lowerTail)
@@ -3,13 +3,21 @@
3
3
  // Written for rStats.js (no ported code). X = 1/Y with Y ~ Gamma(alpha, rate = beta), so with z = beta / x
4
4
  // f(x) = f_Gamma(z; alpha, 1) z / x, P[X <= x] = P[Z >= z], q(p) = beta / q_Gamma(1 - p; alpha, 1)
5
5
  // which keeps the gamma functions' accuracy in both tails. z is formed in double-double and its low part enters to
6
- // first order (the density and the tails are steep in z when alpha is large).
6
+ // first order (the density and the tails are steep in z when alpha is large). Above alpha = 1e15 it is left out: near
7
+ // the centre the low part (up to eps z / 2, z about alpha) is no longer small against the width sqrt(alpha) over which
8
+ // the tails change, so a first-order term is not valid (it gave probabilities of 1e16); the functions are then those
9
+ // at the rounded z (relative errors of order eps sqrt(alpha), the condition of the problem itself).
7
10
  import { vectorize } from "../internal/vectorize.js";
8
- import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
9
- import { standardizeDD } from "../internal/ddexp.js";
10
- import { dgamma1, pgamma1, qgamma1 } from "./gamma.js";
11
+ import { d0, dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
12
+ import { ddExp, logRatioDD, standardizeDD } from "../internal/ddexp.js";
13
+ import { ddAdd, ddLog, ddMulNum, ddSub } from "../special/dd.js";
14
+ import { lgamma } from "../special/gamma.js";
15
+ import { dgamma1, logTinyGammaQuantile, pgamma1, qgamma1 } from "./gamma.js";
11
16
  const valid = (alpha, beta) => alpha > 0 && beta > 0 && Number.isFinite(beta);
12
17
  // alpha = Inf is taken as the limit (the distribution concentrates at 0), as extraDistr does
18
+ const MIN_NORMAL = 2 ** -1022;
19
+ /** Largest alpha for which the low part of z enters to first order (see the top of the file) */
20
+ const MAX_ALPHA_CORRECTED = 1e15;
13
21
  export function dinvgamma1(x, alpha, beta, log) {
14
22
  if (Number.isNaN(x) || !valid(alpha, beta))
15
23
  return NaN;
@@ -20,11 +28,40 @@ export function dinvgamma1(x, alpha, beta, log) {
20
28
  const [z, zl] = standardizeDD(beta, 0, x);
21
29
  if (z === Infinity)
22
30
  return d0(log);
31
+ if (z < MIN_NORMAL) {
32
+ // beta / x subnormal or 0: in logs, log f = alpha log(beta / x) - lgamma(alpha) - log x (e^-z is 1), with
33
+ // log(beta / x) from log beta - log x
34
+ const lr = logRatioDD(beta, x);
35
+ // (where alpha log(beta / x) or lgamma(alpha) overflows the log is -Infinity, which the double-double sums made NaN:
36
+ // dinvgamma(4.9e270, 1.3e306, beta 1.8e-118))
37
+ if (!(Math.abs(lr[0] * alpha) < Infinity) || lgamma(alpha) === Infinity)
38
+ return d0(log);
39
+ const l = ddAdd(ddSub(alpha < 1e300 ? ddMulNum(lr, alpha) : [lr[0] * alpha, 0], ddLog([x, 0])), [-lgamma(alpha), 0]);
40
+ return log ? l[0] + l[1] : l[0] < -746 ? 0 : ddExp(l)[0];
41
+ }
23
42
  // d/dz log(f_Gamma(z) z) = alpha / z - 1
24
- const c = Number.isFinite(zl) ? (alpha / z - 1) * zl : 0;
25
- if (log)
26
- return dgamma1(z, alpha, 1, true) + Math.log(z) - Math.log(x) + c;
27
- return ((dgamma1(z, alpha, 1, false) * z) / x) * (1 + c);
43
+ const c = Number.isFinite(zl) && alpha <= MAX_ALPHA_CORRECTED ? alpha * (zl / z) - zl : 0;
44
+ // f_Gamma(z) z / x from normal factors (undefined where f_Gamma(z) or f_Gamma(z) z is below the normal range, where z
45
+ // or 1 / x can bring the density back)
46
+ const linear = () => {
47
+ const g = dgamma1(z, alpha, 1, false);
48
+ const dz = g * z;
49
+ return g >= MIN_NORMAL && dz >= MIN_NORMAL ? dz / x : undefined;
50
+ };
51
+ if (log) {
52
+ const lg = dgamma1(z, alpha, 1, true);
53
+ const ld = lg + Math.log(z) - Math.log(x) + c;
54
+ if (!(Math.abs(ld) < 0.5 * Math.abs(lg)))
55
+ return ld;
56
+ // log f_Gamma and log(z / x) (hundreds near the ends of the range) cancelled to below half, so their roundings
57
+ // would show: the log of the linear value instead (dinvgamma(9.7e-286, 91.7, beta 2.5e-287, log) was 1.2e-13 off)
58
+ const v = linear();
59
+ return v !== undefined && v >= MIN_NORMAL && v < Infinity ? Math.log(v) + c : ld;
60
+ }
61
+ const v = linear();
62
+ if (v === undefined)
63
+ return Math.exp(dgamma1(z, alpha, 1, true) + Math.log(z) - Math.log(x) + c);
64
+ return v * (1 + c);
28
65
  }
29
66
  export function pinvgamma1(q, alpha, beta, lowerTail, logP) {
30
67
  if (Number.isNaN(q) || !valid(alpha, beta))
@@ -34,14 +71,22 @@ export function pinvgamma1(q, alpha, beta, lowerTail, logP) {
34
71
  if (q === Infinity || alpha === Infinity)
35
72
  return dt1(lowerTail, logP);
36
73
  const [z, zl] = standardizeDD(beta, 0, q);
74
+ if (z < MIN_NORMAL) {
75
+ // beta / x subnormal or 0: P[Z >= z] is the upper tail at beta of the gamma distribution with scale x, which
76
+ // pgamma takes in logs there
77
+ return pgamma1(beta, alpha, q, !lowerTail, logP);
78
+ }
37
79
  const v = pgamma1(z, alpha, 1, !lowerTail, logP);
38
- if (!(zl !== 0 && Number.isFinite(zl) && Number.isFinite(z)))
80
+ if (!(zl !== 0 && Number.isFinite(zl) && Number.isFinite(z) && alpha <= MAX_ALPHA_CORRECTED))
39
81
  return v;
40
82
  // P[Z <= z] grows by f(z) zl, P[Z > z] falls by it
41
83
  const sign = lowerTail ? -1 : 1;
42
84
  if (!logP)
43
85
  return v + sign * dgamma1(z, alpha, 1, false) * zl;
44
- // log P + f(z) zl / P, with f / P from the logs (P may underflow)
86
+ // log P + f(z) zl / P, with f / P from the logs (P may underflow). Beyond |log P| = 1e8 the difference of the logs
87
+ // has lost its digits (eps |log P| absolute) and the correction is below the rounding of log P anyway
88
+ if (!(Math.abs(v) < 1e8))
89
+ return v;
45
90
  const c = sign * Math.exp(dgamma1(z, alpha, 1, true) - v) * zl;
46
91
  return Number.isFinite(c) ? v + c : v;
47
92
  }
@@ -53,6 +98,11 @@ export function qinvgamma1(p, alpha, beta, lowerTail, logP) {
53
98
  return b;
54
99
  if (alpha === Infinity)
55
100
  return 0;
101
+ // A gamma quantile below the smallest normal double has lost digits (or is 0): beta / it from the log
102
+ const { lower, logTarget, linearTarget } = smallerTail(p, !lowerTail, logP);
103
+ const tiny = logTinyGammaQuantile(logTarget, lower, alpha, linearTarget);
104
+ if (tiny !== undefined)
105
+ return Math.log(beta) - tiny[0] > 710 ? Infinity : ddExp(ddSub(ddLog([beta, 0]), tiny))[0];
56
106
  return beta / qgamma1(p, alpha, 1, !lowerTail, logP);
57
107
  }
58
108
  /**