@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
@@ -1,4 +1,19 @@
1
1
  export declare function dnchisq1(x: number, df: number, ncp: number, log: boolean): number;
2
+ /**
3
+ * log f(x) at x = x0 e^v, with the offset v taken exactly where the density varies faster than the rounding of x can
4
+ * follow: in the asymptotic forms the exponent depends on x through sqrt(x) - sqrt(λ) or λ + 2ν - x, which are formed
5
+ * from x0 and v (by expm1) instead of from the double x. Used by integrals over log x (src/distributions/nbeta.ts),
6
+ * where x0 e^v rounded would put an error of eps |d log f / d log x| (eps sqrt(λ) near the mode) into each node.
7
+ */
8
+ export declare function dnchisqLogNear(x0: number, v: number, df: number, ncp: number): number;
9
+ /**
10
+ * P(s, t) (lower) or Q(s, t) of the central gamma distribution (its log if log) for a large shape (s > 1e4), as the
11
+ * central χ² with 2s degrees of freedom through debyeTails (λ = 0; the uniform expansion then reduces to Stirling's
12
+ * series), at t = t0 e^v with the offset v exact: N = 2s - 2 - 2t is formed from t0 and v (src/distributions/nbeta.ts
13
+ * integrates over log t, where the rounding of t0 e^v would carry an error of eps sqrt(s) into the log). The
14
+ * incomplete gamma function can take 40 ms for such shapes (s = 1e12, t < s; 0.1 s at s = 1e37)
15
+ */
16
+ export declare function gammaTailNear(s: number, t0: number, v: number, lower: boolean, log: boolean): number;
2
17
  export declare function pnchisq1(q: number, df: number, ncp: number, lowerTail: boolean, logP: boolean): number;
3
18
  /**
4
19
  * A tail that a rigorous bound places below the smallest positive double: `far` is "lower" when P[X <= q] is
@@ -10,4 +25,14 @@ export type FarTail = "lower" | "upper" | undefined;
10
25
  * (log 0). The log of the far tail is left to the full computation (undefined).
11
26
  */
12
27
  export declare function negligibleTail(far: FarTail, lowerTail: boolean, logP: boolean): number | undefined;
28
+ /**
29
+ * The quantile x found by the Newton iteration if its log probability lp is within 1e-15 of the target, or within 1e-9
30
+ * and x is the quantile to 1e-14 (x reaches the target and x (1 - 1e-14) does not: where the distribution function is
31
+ * nearly flat in log x the iteration can stall 1e-8 away in log p, and where it is steep in log x, 1e-12 in log p can
32
+ * be 4e-13 in x), otherwise that of `search`. The iteration fails where the distribution function is too steep to be
33
+ * resolved by the doubles (for a huge df or ncp the spread can be below the spacing of x, so that the function steps
34
+ * from 0 to 1/2 at one double); a search over the doubles (searchDoubles) then gives the smallest x that reaches the
35
+ * target
36
+ */
37
+ export declare function confirmQuantile(x: number, lp: number, logTarget: number, search: () => number, passes: (x: number) => boolean): number;
13
38
  export declare function qnchisq1(p: number, df: number, ncp: number, lowerTail: boolean, logP: boolean): number;
@@ -9,16 +9,23 @@
9
9
  // Quantiles use Newton's method starting from Patnaik's (1949) approximation (c χ²_ν, c = (k + 2λ)/(k + λ),
10
10
  // ν = (k + λ)^2/(k + 2λ)).
11
11
  // With a huge λ the mixture is slow and inaccurate far from the centre; there a Chernoff bound decides first whether
12
- // the far tail is below the double range (then it is 0 and the near tail 1). For x λ > 4e18 the density comes from the
13
- // large-argument expansion of the Bessel function and the distribution function from integrating it numerically.
12
+ // the far tail is below the double range (then it is 0 and the near tail 1). Where the mixture's terms spread over
13
+ // too many indices (the Bessel argument z = sqrt(λ x) large, or ν = k/2 - 1 large) the density f(x) =
14
+ // exp(-(x+λ)/2) (x/λ)^(ν/2) I_ν(z) / 2 comes from an asymptotic expansion of the Bessel function (the large-argument
15
+ // one where ν² <= z/100, the uniform one in ν otherwise) and the distribution function from integrating it numerically
16
+ // (asymptoticMethod). Quantiles whose distribution function steps within a few doubles end in a search over the doubles.
14
17
  import { dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
15
18
  import { invertContinuous } from "../internal/invert.js";
16
- import { dpoisLogDD, mixtureCdf, mixtureCdfBoth, mixtureDensity } from "../internal/poissonMixture.js";
19
+ import { kronrodAdaptive, narrowQuantile, quadratureControl, searchDoubles } from "../internal/noncentral.js";
20
+ import { dpoisLogDD, mixtureCdf, mixtureDensity, mixtureTail } from "../internal/poissonMixture.js";
17
21
  import { gammaInc } from "../special/igam.js";
18
22
  import { dpoisRaw } from "../special/loader.js";
19
23
  import { ddAdd, ddDiv, twoProd, twoSum } from "../special/dd.js";
20
24
  import { digamma } from "../special/psigamma.js";
25
+ import { lgamma1p } from "../special/gamma.js";
26
+ import { log1pmx } from "../special/log1pmx.js";
21
27
  import { dgamma1, qgamma1 } from "./gamma.js";
28
+ import { qnorm } from "./normal.js";
22
29
  function gammaKernel(a, y) {
23
30
  // For very small y the ratio y/(a+j) underflows, so keep it scaled by 2^500
24
31
  const tiny = y < 1e-250;
@@ -28,16 +35,29 @@ function gammaKernel(a, y) {
28
35
  cdf: (j, lower, log) => gammaInc(a + j, y, lower, log),
29
36
  inc: (j, log) => {
30
37
  const [s, corr] = incCorrection(a, j, y);
38
+ if (s < 1e-8) {
39
+ const l = tinyShapeLog(s, y);
40
+ return log ? l : Math.exp(l);
41
+ }
31
42
  return log ? dpoisRaw(s, y, true) + corr : dpoisRaw(s, y, false) * (1 + corr);
32
43
  },
33
44
  // d_j / d_{j-1} = y / (a + j)
34
45
  ratio: (j) => ddDiv([ys, 0], twoSum(a, j)),
35
46
  incLogDD: (j) => {
36
47
  const [s, corr] = incCorrection(a, j, y);
48
+ if (s < 1e-8)
49
+ return ddAdd([-y, 0], [s * Math.log(y) - lgamma1p(s), 0]);
37
50
  return ddAdd(dpoisLogDD(s, y), [corr, 0]);
38
51
  },
39
52
  };
40
53
  }
54
+ /**
55
+ * log d_0 = s log y - y - log Γ(1 + s) for a tiny shape s (df < 2e-8): dpoisRaw's Stirling form cancels there (its terms
56
+ * are of order log s, 255 at s = 1e-222, and lose that many ulps)
57
+ */
58
+ function tinyShapeLog(s, y) {
59
+ return s * Math.log(y) - y - lgamma1p(s);
60
+ }
41
61
  /**
42
62
  * The shape a + j rounded to double, s, and the first-order change in log d_j from s to the exact a + j:
43
63
  * δ ∂log d/∂s with δ the rounding and ∂log dpois(s; y)/∂s = log y - ψ(s + 1). Far in a tail |log y - ψ(s + 1)| is
@@ -54,28 +74,31 @@ function validParams(df, ncp) {
54
74
  }
55
75
  /**
56
76
  * Linear value and log of P[X <= x] (lower) / P[X > x] (x > 0 finite, ncp > 0).
57
- * The log of a value near 1 is built with log1p from the small value of the other side
77
+ * A value near 1, and its log, are built from the small value of the other side
58
78
  */
59
79
  function pnchisqBoth(x, df, ncp, lower) {
60
80
  const mu = ncp / 2;
61
- // x λ is very large: the peak of the series is too far away, so integrate the density (besselAsymptotic)
62
- if (mu * (x / 2) > 1e18)
63
- return besselTails(x, df, ncp, lower);
81
+ // The series has too many terms (or gammaInc is slow for its huge shapes): integrate an asymptotic form of the density
82
+ const method = asymptoticMethod(df, besselArg(x, ncp));
83
+ if (method !== undefined)
84
+ return method === "hankel" ? besselTails(x, df, ncp, lower) : debyeTails(x, df, ncp, lower);
64
85
  // x so small that x/2 underflows to 0 (the smallest subnormal) is approximated by the smallest positive number
65
86
  const kernel = gammaKernel(df / 2, Math.max(x / 2, Number.MIN_VALUE));
66
- const own = mixtureCdfBoth(mu, kernel, lower);
67
- if (own.lin > 0.5) {
68
- // The log of a value near 1 is built with log1p from the small value of the other side (computed only when the log is needed)
87
+ if (mu > 1e8 && !lower) {
88
+ // With a large λ (here x is far below the mean k + λ, as z is small) the upper sum would start about 10 sqrt(λ/2)
89
+ // terms below λ/2 and take as many steps; the lower tail is the small one, so build the upper from it
90
+ const p = mixtureCdf(mu, kernel, true, false);
69
91
  let lg;
70
92
  return {
71
- lin: own.lin,
93
+ lin: 1 - p,
72
94
  get log() {
73
- lg ??= Math.log1p(-mixtureCdf(mu, kernel, !lower, false));
95
+ lg ??= Math.log1p(-p);
74
96
  return lg;
75
97
  },
76
98
  };
77
99
  }
78
- return own;
100
+ // (the lower tail is likely the smaller below the mean k + λ)
101
+ return mixtureTail(mu, kernel, lower, x < df + ncp);
79
102
  }
80
103
  function pnchisqRaw(x, df, ncp, lower, log) {
81
104
  const v = pnchisqBoth(x, df, ncp, lower);
@@ -98,32 +121,95 @@ function memoCdf(df, ncp) {
98
121
  /** Core of the log density (x > 0 finite, ncp > 0) */
99
122
  function dnchisqRaw(x, df, ncp, log) {
100
123
  const a = df / 2;
101
- const y = x / 2;
124
+ // (x so small that x/2 underflows to 0 is approximated by the smallest positive number, as in pnchisqBoth)
125
+ const y = Math.max(x / 2, Number.MIN_VALUE);
102
126
  const mu = ncp / 2;
103
- // The ratio of terms w_j g_j is mu y / (j (a + j - 1)); the peak is at the j where it equals 1
104
- const jStar = (-(a - 1) + Math.sqrt((a - 1) * (a - 1) + 4 * mu * y)) / 2;
105
- if (mu * y > 1e18)
127
+ const z = besselArg(x, ncp);
128
+ const method = asymptoticMethod(df, z);
129
+ if (method === "hankel")
106
130
  return besselAsymptotic(x, df, ncp, log);
131
+ if (method === "debye") {
132
+ const l = debyeAt(x, df, ncp).logf;
133
+ return log ? l : Math.exp(l);
134
+ }
135
+ // The ratio of terms w_j g_j is mu y / (j (a + j - 1)) = (z/2)² / (j (a + j - 1)); the peak is at the j where it
136
+ // equals 1, the positive root of j² + (a - 1) j - (z/2)² (written without cancellation for a > 1)
137
+ const jStar = a > 1 ? (z * z) / 2 / (a - 1 + Math.hypot(a - 1, z)) : (-(a - 1) + Math.hypot(a - 1, z)) / 2;
107
138
  // Component density y^(a+j-1) e^-y / Gamma(a+j) = d_j (a + j) / y
108
139
  return mixtureDensity(mu, gammaKernel(a, y), (j) => a + j, jStar, x, log);
109
140
  }
141
+ /** sqrt(λ x), the argument of the Bessel function in the density (without overflow) */
142
+ function besselArg(x, ncp) {
143
+ return Math.sqrt(ncp) * Math.sqrt(x);
144
+ }
145
+ /**
146
+ * Above these Bessel arguments z the asymptotic expansions of I_ν(z) replace the mixture, whose terms spread over
147
+ * about sqrt(z) indices (min(sqrt(z), z / sqrt(ν)) for large ν): the large-argument expansion where it applies, and
148
+ * the uniform expansion in ν for the other ν (then ν > 100)
149
+ */
150
+ const Z_HANKEL = 1e4;
151
+ const Z_ASYMPTOTIC = 1e6;
152
+ /**
153
+ * Above this ν the uniform expansion replaces the mixture at any z (it holds uniformly in z; the incomplete gamma
154
+ * function of the mixture's components can take 0.1 s for shapes of 1e37)
155
+ */
156
+ const NU_UNIFORM = 1e4;
157
+ /**
158
+ * The asymptotic expansion of I_ν(z) used, if any: the large-argument expansion (besselAsymptotic) where ν² <= z/100,
159
+ * so that its terms fall by a factor 200 or more from the first, otherwise the uniform expansion in ν (debyeAt; then
160
+ * ν > 100, where the large-argument expansion diverges for ν² >> z). Undefined: sum the mixture
161
+ */
162
+ function asymptoticMethod(df, z) {
163
+ const nu = df / 2 - 1;
164
+ if (z > Z_HANKEL && nu * nu <= z / 100)
165
+ return "hankel";
166
+ return z > Z_ASYMPTOTIC || nu > NU_UNIFORM ? "debye" : undefined;
167
+ }
168
+ /**
169
+ * sqrt(x) - sqrt(λ) in double-double, as (x - λ)/(sqrt(x) + sqrt(λ)) with the roots in double-double: the rounding of
170
+ * a root would put a relative error of 1e-16 into d, and so an error of 1e-16 d² into the exponent -d²/2 (2e-14 of the
171
+ * density at d = 14)
172
+ */
173
+ function rootDiff(x, ncp) {
174
+ return ddDiv(twoSum(x, -ncp), ddAdd(sqrtDD(x), sqrtDD(ncp)));
175
+ }
176
+ /** sqrt(x) in double-double (one Newton correction of the rounded root) */
177
+ function sqrtDD(x) {
178
+ const s = Math.sqrt(x);
179
+ const [p, pe] = twoProd(s, s);
180
+ return [s, (x - p - pe) / (2 * s)];
181
+ }
182
+ /** The square of a double-double, as the pair [p, e] of twoProd with the cross term added to e */
183
+ function squareDD(d) {
184
+ const [p, pe] = twoProd(d[0], d[0]);
185
+ return [p, pe + 2 * d[0] * d[1]];
186
+ }
187
+ /**
188
+ * log(sqrt(x)/sqrt(λ)) = log(1 + d/sqrt(λ)) for d = sqrt(x) - sqrt(λ) (computed without cancellation by the caller).
189
+ * Far below sqrt(λ) the ratio d/sqrt(λ) rounds to -1, so the log is taken of x and λ themselves
190
+ */
191
+ function logRootRatio(d, rl, x) {
192
+ return d / rl > -0.5 ? Math.log1p(d / rl) : 0.5 * Math.log(x) - Math.log(rl);
193
+ }
110
194
  /**
111
195
  * Density for very large x λ. Apply to f(x) = exp(-(x+λ)/2) (x/λ)^(ν/2) I_ν(sqrt(λ x)) / 2 (ν = k/2 - 1) the
112
196
  * large-z asymptotic expansion of I_ν(z), e^z / sqrt(2 pi z) Σ_m (-1)^m a_m(ν) / z^m.
113
- * (The series cannot be summed because its peak j ≈ sqrt(λ x / 4) is too far out. z > 1e9, so the expansion converges in a few terms)
197
+ * (The series cannot be summed because its peak j ≈ sqrt(λ x / 4) is too far out. z > 1e4 and ν² <= z/100, so the
198
+ * expansion converges in a few terms)
114
199
  */
115
- function besselAsymptotic(x, df, ncp, log) {
200
+ function besselAsymptotic(x, df, ncp, log, dGiven) {
116
201
  const nu = df / 2 - 1;
117
- const z = Math.sqrt(ncp * x);
202
+ const z = besselArg(x, ncp);
118
203
  const s = besselSeries(nu, z);
119
- // -(x + λ)/2 + z = -(sqrt(x) - sqrt(λ))^2 / 2, with sqrt(x) - sqrt(λ) written without cancellation (the difference
120
- // of the rounded roots carries an error of ulp(sqrt(λ))) and its square in double-double, as in besselTails
204
+ // -(x + λ)/2 + z = -(sqrt(x) - sqrt(λ))^2 / 2, with sqrt(x) - sqrt(λ) in double-double (rootDiff) and its square
205
+ // too, as in besselTails (dGiven: that difference from the caller, for an x known more precisely than its double)
121
206
  const rl = Math.sqrt(ncp);
122
- const d = (x - ncp) / (Math.sqrt(x) + rl);
123
- const [p, pe] = twoProd(d, d);
207
+ const dd = dGiven ?? rootDiff(x, ncp);
208
+ const d = dd[0] + dd[1];
209
+ const [p, pe] = squareDD(dd);
124
210
  const hi = -p / 2;
125
211
  // (ν/2) log(x/λ) = ν log(sqrt(x)/sqrt(λ))
126
- const rest = -Math.LN2 - pe / 2 + nu * Math.log1p(d / rl) - 0.5 * Math.log(2 * Math.PI * z) + Math.log(s);
212
+ const rest = -Math.LN2 - pe / 2 + nu * logRootRatio(d, rl, x) - 0.5 * Math.log(2 * Math.PI * z) + Math.log(s);
127
213
  if (log)
128
214
  return hi + rest;
129
215
  return hi > -700 ? Math.exp(hi) * Math.exp(rest) : Math.exp(hi + rest);
@@ -162,15 +248,21 @@ function besselTails(x, df, ncp, lower) {
162
248
  const rl = Math.sqrt(ncp);
163
249
  const t0 = Math.sqrt(x);
164
250
  // t0 - sqrt(λ) without cancellation
165
- const d0 = (x - ncp) / (t0 + rl);
166
- const mode = (rl + Math.sqrt(Math.max(ncp + 4 * c, 0))) / 2;
167
- const up = t0 >= mode;
251
+ const d0dd = rootDiff(x, ncp);
252
+ const d0 = d0dd[0] + d0dd[1];
253
+ // Side of the mode (rl + sqrt(λ + 4c))/2, compared through its offset from sqrt(λ): t0 itself rounds to sqrt(λ) for x
254
+ // within an ulp or two of a huge λ, where d0 can still be far from 0
255
+ const modeOffset = ncp + 4 * c >= 0 ? (2 * c) / (Math.sqrt(ncp + 4 * c) + rl) : -rl / 2;
256
+ const up = d0 >= modeOffset;
168
257
  const dir = up ? 1 : -1;
169
258
  const ls0 = Math.log(besselSeries(nu, t0 * rl));
170
259
  // log(g(t0 + dir u) / g(t0)), written with the offset h so that it has no cancellation near u = 0
171
260
  const integrand = (u) => {
172
261
  const h = dir * u;
173
- return Math.exp((-h * (2 * d0 + h)) / 2 + c * Math.log1p(h / t0) + Math.log(besselSeries(nu, (t0 + h) * rl)) - ls0);
262
+ const v = Math.exp((-h * (2 * d0 + h)) / 2 + c * Math.log1p(h / t0) + Math.log(besselSeries(nu, (t0 + h) * rl)) - ls0);
263
+ // Below the mode the integral runs down to t = 0, where the expansion of S fails (z = t sqrt(λ) small); g is
264
+ // negligible there (a factor e^-(z0 - z) or less), so a non-finite value is taken as 0
265
+ return Number.isFinite(v) ? v : 0;
174
266
  };
175
267
  // Rate at which log g falls at distance u from t0 (the derivative of log g, without the O(1/(t sqrt(λ))) part of S)
176
268
  const rate = (u) => -dir * (c / (t0 + dir * u) - (d0 + dir * u));
@@ -180,61 +272,133 @@ function besselTails(x, df, ncp, lower) {
180
272
  let w = 1 / (1 + Math.abs(rate(0)));
181
273
  let a = 0;
182
274
  let sum = 0;
275
+ const control = quadratureControl();
183
276
  for (let i = 0; i < 200 && a < end; i++) {
184
277
  const b = Math.min(a + w, end);
185
- sum += kronrodAdaptive(integrand, a, b, sum, 0);
278
+ sum += kronrodAdaptive(integrand, a, b, sum, 0, control);
186
279
  const r = rate(b);
187
280
  if (r > 0 && integrand(b) <= 1e-17 * r * sum)
188
281
  break;
189
282
  a = b;
190
283
  w *= 2;
191
284
  }
192
- const [p, pe] = twoProd(d0, d0);
285
+ const [p, pe] = squareDD(d0dd);
193
286
  const hi = -p / 2;
194
- const rest = -pe / 2 + c * Math.log1p(d0 / rl) - LN_SQRT_2PI + ls0 + Math.log(sum);
287
+ const rest = -pe / 2 + c * logRootRatio(d0, rl, x) - LN_SQRT_2PI + ls0 + Math.log(sum);
195
288
  const tail = hi > -700 ? Math.exp(hi) * Math.exp(rest) : Math.exp(hi + rest);
196
289
  if (up !== lower)
197
290
  return { lin: tail, log: hi + rest };
198
291
  return { lin: 1 - tail, log: Math.log1p(-tail) };
199
292
  }
200
- // Gauss-Kronrod 7-15 rule (QUADPACK, public domain; as in src/integrate/quadpack.ts): Kronrod nodes, from the end of
201
- // [-1, 1] to the centre, their weights, and the Gauss weights of the odd-numbered nodes
202
- const GK15_X = [
203
- 0.991455371120812639206854697526329, 0.949107912342758524526189684047851, 0.864864423359769072789712788640926,
204
- 0.741531185599394439863864773280788, 0.58608723546769113029414483825873, 0.405845151377397166906606412076961,
205
- 0.207784955007898467600689403773245, 0,
206
- ];
207
- const GK15_WK = [
208
- 0.02293532201052922496373200805897, 0.063092092629978553290700663189204, 0.104790010322250183839876322541518,
209
- 0.140653259715525918745189590510238, 0.16900472663926790282658342659855, 0.190350578064785409913256402421014,
210
- 0.204432940075298892414161999234649, 0.209482141084727828012999174891714,
211
- ];
212
- const GK15_WG = [
213
- 0.129484966168869693270611432679082, 0.27970539148927666790146777142378, 0.381830050505118944950369775488975,
214
- 0.417959183673469387755102040816327,
215
- ];
216
293
  /**
217
- * Integral of f over [a, b] by the 15-point Kronrod rule, bisecting while it differs from the 7-point Gauss rule by
218
- * more than 1e-15 of the total (`total`, the integral accumulated so far, or this part's own value). The difference
219
- * overestimates the error of the Kronrod value by far, so the result is good to about the rounding of the sum
294
+ * Polynomials U_k(p) of the uniform asymptotic expansion of I_ν(ν w) (DLMF 10.41.3, 10.41.10), as coefficients of
295
+ * p^0, p^1, ..., built with the recurrence U_(k+1)(p) = p²(1 - p²) U_k'(p) / 2 + ∫_0^p (1 - 5t²) U_k(t) dt / 8
296
+ * (DLMF 10.41.11). |U_k(p)| <= 1.1 on [0, 1] for k <= 10 (11 at k = 12).
297
+ */
298
+ const DEBYE_U = (() => {
299
+ const us = [[1]];
300
+ for (let k = 1; k <= 12; k++) {
301
+ const u = us[k - 1];
302
+ const v = new Array(u.length + 3).fill(0);
303
+ u.forEach((c, i) => {
304
+ if (c === 0)
305
+ return;
306
+ v[i + 1] = v[i + 1] + (i * c) / 2 + c / (8 * (i + 1));
307
+ v[i + 3] = v[i + 3] - (i * c) / 2 - (5 * c) / (8 * (i + 3));
308
+ });
309
+ us.push(v);
310
+ }
311
+ return us;
312
+ })();
313
+ /** Σ_k U_k(p) / ν^k of the uniform expansion (ν > 100: the terms left out are below 1e-19) */
314
+ function debyeSeries(nu, p) {
315
+ let s = 1;
316
+ let scale = 1;
317
+ for (let k = 1; k < DEBYE_U.length; k++) {
318
+ scale /= nu;
319
+ if (scale < 1e-20)
320
+ break;
321
+ const c = DEBYE_U[k];
322
+ let v = 0;
323
+ for (let i = c.length - 1; i >= 0; i--)
324
+ v = v * p + c[i];
325
+ s += v * scale;
326
+ }
327
+ return s;
328
+ }
329
+ /**
330
+ * Density for large ν (asymptoticMethod), from the uniform expansion of I_ν(ν w), w = z/ν
331
+ * (DLMF 10.41.3: e^(νη) / (sqrt(2 pi ν) (1 + w²)^(1/4)) Σ_k U_k(p) / ν^k, p = (1 + w²)^(-1/2),
332
+ * νη = R + ν log(z / (ν + R)), R = sqrt(ν² + z²)):
333
+ * log f(x) = -log 2 + E - log sqrt(2 pi) - log(R)/2 + log Σ_k U_k(ν/R) / ν^k,
334
+ * E = -(x + λ)/2 + R + ν log(x / (ν + R)).
335
+ * The terms of E are of order x (1e6 or more here) where E can be of order 1. In r = x/(ν + R) (so that
336
+ * x = r (λ r + 2ν), R = λ r + ν) the exponent is the sum of two terms that are never positive,
337
+ * E = -(λ/2) e² + ν (log(1 + e) - e), e = r - 1,
338
+ * and e = (x - ν - R)/(ν + R) = -x N / (D (ν + R)), N = λ + 2ν - x (in double-double),
339
+ * D = x - ν + R = x + z²/(R + ν), has no cancellation either.
340
+ */
341
+ function debyeAt(x, df, ncp, nGiven) {
342
+ const nu = df / 2 - 1;
343
+ const z = besselArg(x, ncp);
344
+ const R = Math.hypot(nu, z);
345
+ const rn = R + nu;
346
+ // (nGiven: N from the caller, for an x known more precisely than its double)
347
+ const N = nGiven ?? ddSum(ddAdd(ddAdd(twoSum(ncp, df), [-2, 0]), [-x, 0]));
348
+ const D = x + z * (z / rn);
349
+ const e = -(x / D) * (N / rn);
350
+ const ls = Math.log(debyeSeries(nu, nu / R));
351
+ // log(1 + e) - e; far below the mode e rounds to -1, and log(1 + e) = log r is taken from x and ν + R
352
+ const lm = e > -0.5 ? log1pmx(e) : Math.log(x) - Math.log(rn) - e;
353
+ const logf = -Math.LN2 - (ncp / 2) * e * e + nu * lm - LN_SQRT_2PI - 0.5 * Math.log(R) + ls;
354
+ return { r: x / rn, e, R, ls, logf };
355
+ }
356
+ /**
357
+ * Linear value and log of P[X <= x] (lower) / P[X > x] for large ν (asymptoticMethod), by integrating the density
358
+ * of debyeAt, as besselTails does in sqrt(x), here in r: dx = 2R dr, so the density in r is
359
+ * g(r) = exp(E) sqrt(R) S / sqrt(2 pi), log g = -(λ/2) e² + ν (log(1 + e) - e) + log(R)/2 - log sqrt(2 pi) + log S,
360
+ * which reduces to that of besselTails for ν = 0 (r = t/sqrt(λ)). log g is concave (its second derivative is
361
+ * -λ - ν/r² up to O(1/R)), with its mode near e = 0. With r = r0 + h,
362
+ * log(g(r)/g(r0)) = -(λ/2) h (h + 2 e0) - ν h e0 / r0 + ν (log(1 + h/r0) - h/r0) + log(1 + λ h / R0)/2 + log(S/S0),
363
+ * whose terms all have the sign of the result away from the mode.
220
364
  */
221
- function kronrodAdaptive(f, a, b, total, depth) {
222
- const m = (a + b) / 2;
223
- const h = (b - a) / 2;
224
- const fc = f(m);
225
- let k = GK15_WK[7] * fc;
226
- let g = GK15_WG[3] * fc;
227
- for (let j = 0; j < 7; j++) {
228
- const fs = f(m - h * GK15_X[j]) + f(m + h * GK15_X[j]);
229
- k += GK15_WK[j] * fs;
230
- if (j % 2 === 1)
231
- g += GK15_WG[(j - 1) / 2] * fs;
365
+ function debyeTails(x, df, ncp, lower, nGiven) {
366
+ const nu = df / 2 - 1;
367
+ const { r: r0, e: e0, R: R0, ls: ls0, logf } = debyeAt(x, df, ncp, nGiven);
368
+ // Derivative of log g at r = r0 + h (without the O(1/R²) part of S)
369
+ const slope = (h) => -(e0 + h) * (ncp + nu / (r0 + h)) + ncp / (2 * (R0 + ncp * h));
370
+ const up = slope(0) <= 0;
371
+ const dir = up ? 1 : -1;
372
+ const integrand = (u) => {
373
+ const h = dir * u;
374
+ const R = R0 + ncp * h;
375
+ const v = Math.exp(-(ncp / 2) * h * (h + 2 * e0) - (nu * h * e0) / r0 + nu * log1pmx(h / r0) + 0.5 * Math.log1p((ncp * h) / R0) +
376
+ Math.log(debyeSeries(nu, nu / R)) - ls0);
377
+ return Number.isNaN(v) ? 0 : v;
378
+ };
379
+ const rate = (u) => -dir * slope(dir * u);
380
+ // Integrate over intervals of doubling width from about the width over which g falls by e^-1; the rest beyond u is
381
+ // at most g(u)/rate(u) (log-concavity)
382
+ const end = up ? Infinity : r0;
383
+ let w = 1 / (Math.abs(rate(0)) + Math.hypot(Math.sqrt(ncp), Math.sqrt(nu) / r0));
384
+ let a = 0;
385
+ let sum = 0;
386
+ const control = quadratureControl();
387
+ for (let i = 0; i < 200 && a < end; i++) {
388
+ const b = Math.min(a + w, end);
389
+ sum += kronrodAdaptive(integrand, a, b, sum, 0, control);
390
+ const rb = rate(b);
391
+ if (rb > 0 && integrand(b) <= 1e-17 * rb * sum)
392
+ break;
393
+ a = b;
394
+ w *= 2;
232
395
  }
233
- k *= h;
234
- g *= h;
235
- if (Math.abs(k - g) <= 1e-15 * Math.max(Math.abs(k), total) || depth >= 40)
236
- return k;
237
- return kronrodAdaptive(f, a, m, total, depth + 1) + kronrodAdaptive(f, m, b, total, depth + 1);
396
+ // g(r0) = f(x0) 2 R0
397
+ const lt = logf + Math.log(2 * R0) + Math.log(sum);
398
+ const tail = Math.exp(lt);
399
+ if (up !== lower)
400
+ return { lin: tail, log: lt };
401
+ return { lin: 1 - tail, log: Math.log1p(-tail) };
238
402
  }
239
403
  export function dnchisq1(x, df, ncp, log) {
240
404
  if (Number.isNaN(x) || Number.isNaN(df) || Number.isNaN(ncp))
@@ -255,6 +419,47 @@ export function dnchisq1(x, df, ncp, log) {
255
419
  }
256
420
  return dnchisqRaw(x, df, ncp, log);
257
421
  }
422
+ /** The value of a double-double */
423
+ function ddSum(v) {
424
+ return v[0] + v[1];
425
+ }
426
+ /**
427
+ * log f(x) at x = x0 e^v, with the offset v taken exactly where the density varies faster than the rounding of x can
428
+ * follow: in the asymptotic forms the exponent depends on x through sqrt(x) - sqrt(λ) or λ + 2ν - x, which are formed
429
+ * from x0 and v (by expm1) instead of from the double x. Used by integrals over log x (src/distributions/nbeta.ts),
430
+ * where x0 e^v rounded would put an error of eps |d log f / d log x| (eps sqrt(λ) near the mode) into each node.
431
+ */
432
+ export function dnchisqLogNear(x0, v, df, ncp) {
433
+ const x = Math.abs(v) < 700 ? x0 * Math.exp(v) : Math.exp(Math.log(x0) + v);
434
+ if (!(x > 0 && x < Infinity) || !validParams(df, ncp) || ncp === 0)
435
+ return dnchisq1(x, df, ncp, true);
436
+ const method = asymptoticMethod(df, besselArg(x, ncp));
437
+ if (method === "hankel") {
438
+ return besselAsymptotic(x, df, ncp, true, ddAdd(rootDiff(x0, ncp), [Math.sqrt(x0) * Math.expm1(v / 2), 0]));
439
+ }
440
+ if (method === "debye") {
441
+ const n0 = ddAdd(ddAdd(twoSum(ncp, df), [-2, 0]), [-x0, 0]);
442
+ return debyeAt(x, df, ncp, ddSum(ddAdd(n0, [-x0 * Math.expm1(v), 0]))).logf;
443
+ }
444
+ return dnchisqRaw(x, df, ncp, true);
445
+ }
446
+ /**
447
+ * P(s, t) (lower) or Q(s, t) of the central gamma distribution (its log if log) for a large shape (s > 1e4), as the
448
+ * central χ² with 2s degrees of freedom through debyeTails (λ = 0; the uniform expansion then reduces to Stirling's
449
+ * series), at t = t0 e^v with the offset v exact: N = 2s - 2 - 2t is formed from t0 and v (src/distributions/nbeta.ts
450
+ * integrates over log t, where the rounding of t0 e^v would carry an error of eps sqrt(s) into the log). The
451
+ * incomplete gamma function can take 40 ms for such shapes (s = 1e12, t < s; 0.1 s at s = 1e37)
452
+ */
453
+ export function gammaTailNear(s, t0, v, lower, log) {
454
+ const t = Math.abs(v) < 700 ? t0 * Math.exp(v) : Math.exp(Math.log(t0) + v);
455
+ if (!(t > 0))
456
+ return lower ? (log ? -Infinity : 0) : log ? 0 : 1;
457
+ if (t === Infinity)
458
+ return lower ? (log ? 0 : 1) : log ? -Infinity : 0;
459
+ const n = ddAdd(ddAdd(twoSum(2 * s, -2), [-2 * t0, 0]), [-2 * t0 * Math.expm1(v), 0]);
460
+ const r = debyeTails(2 * t, 2 * s, 0, lower, ddSum(n));
461
+ return log ? r.log : r.lin;
462
+ }
258
463
  export function pnchisq1(q, df, ncp, lowerTail, logP) {
259
464
  if (Number.isNaN(q) || Number.isNaN(df) || Number.isNaN(ncp))
260
465
  return NaN;
@@ -306,22 +511,43 @@ export function negligibleTail(far, lowerTail, logP) {
306
511
  * Both exponents are convex in s and are smallest at u = 1 ± 2s = (k + sqrt(k² + 4qλ)) / (2q), the positive root of
307
512
  * q u² - k u - λ = 0: u > 1 (q below the mean k + λ) for the lower tail, u < 1 for the upper. Returns the tail whose
308
513
  * bound is below the double range.
514
+ * Near the mean the terms of the exponents (of order q s) cancel; with the root they reduce to
515
+ * -2q s² - (k/2) (log(1 ± 2s) ∓ 2s), s = |λ + k - q| / (2q + 4qλ / (sqrt(k² + 4qλ) + k)),
516
+ * whose terms are both of order s² (q s² and k s²) instead of q s (λ + k - q in double-double).
309
517
  */
310
518
  function chisqTailBound(q, df, ncp) {
311
- const u = (df + Math.sqrt(df * df + 4 * q * ncp)) / (2 * q);
312
- if (!Number.isFinite(u))
519
+ const [h, l] = ddAdd(twoSum(ncp, df), [-q, 0]);
520
+ const diff = h + l;
521
+ const root = Math.hypot(df, 2 * Math.sqrt(q) * Math.sqrt(ncp));
522
+ const s = Math.abs(diff) / (2 * q + 4 * q * (ncp / (root + df)));
523
+ if (!(s > 0) || !Number.isFinite(s))
313
524
  return undefined;
314
- if (u > 1) {
315
- const s = (u - 1) / 2;
316
- const lb = s * q - (df / 2) * Math.log(u) - (ncp * s) / u;
317
- return lb < LOG_NEGLIGIBLE ? "lower" : undefined;
318
- }
319
- if (u < 1 && u > 0) {
320
- const s = (1 - u) / 2;
321
- const lb = -s * q - (df / 2) * Math.log(u) + (ncp * s) / u;
322
- return lb < LOG_NEGLIGIBLE ? "upper" : undefined;
323
- }
324
- return undefined;
525
+ const sign = diff > 0 ? 1 : -1;
526
+ // The reduced form cancels in turn for large s, where q is far below the mean: there the direct form, with
527
+ // u = 1 ± 2s (s can be near the overflow threshold for a tiny q, so log u and λs/u are formed without u)
528
+ const lb = s <= 0.25
529
+ ? -2 * q * s * s - (df / 2) * log1pmx(2 * sign * s)
530
+ : sign > 0
531
+ ? s * q - (df / 2) * (Math.LN2 + Math.log(s + 0.5)) - ncp / (2 + 1 / s)
532
+ : -s * q - (df / 2) * Math.log1p(-2 * s) + (ncp * s) / (1 - 2 * s);
533
+ if (!(lb < LOG_NEGLIGIBLE))
534
+ return undefined;
535
+ return diff > 0 ? "lower" : "upper";
536
+ }
537
+ /**
538
+ * The quantile x found by the Newton iteration if its log probability lp is within 1e-15 of the target, or within 1e-9
539
+ * and x is the quantile to 1e-14 (x reaches the target and x (1 - 1e-14) does not: where the distribution function is
540
+ * nearly flat in log x the iteration can stall 1e-8 away in log p, and where it is steep in log x, 1e-12 in log p can
541
+ * be 4e-13 in x), otherwise that of `search`. The iteration fails where the distribution function is too steep to be
542
+ * resolved by the doubles (for a huge df or ncp the spread can be below the spacing of x, so that the function steps
543
+ * from 0 to 1/2 at one double); a search over the doubles (searchDoubles) then gives the smallest x that reaches the
544
+ * target
545
+ */
546
+ export function confirmQuantile(x, lp, logTarget, search, passes) {
547
+ const r = Math.abs(lp - logTarget) / Math.max(1, Math.abs(logTarget));
548
+ if (r <= 1e-15 || (r <= 1e-9 && passes(x) && !passes(x * (1 - 1e-14))))
549
+ return x;
550
+ return search();
325
551
  }
326
552
  export function qnchisq1(p, df, ncp, lowerTail, logP) {
327
553
  if (Number.isNaN(p) || Number.isNaN(df) || Number.isNaN(ncp))
@@ -342,26 +568,36 @@ export function qnchisq1(p, df, ncp, lowerTail, logP) {
342
568
  return qgamma1(p, df / 2, 2, lowerTail, logP);
343
569
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
344
570
  const cdf = memoCdf(df, ncp);
345
- // If the distribution function at the smallest positive number already passes the target, the answer is 0 (includes the point mass for df = 0)
346
- // (the upper tail there is built from the lower one: the series for the upper tail itself takes seconds for λ = 1e12)
347
- const atMin = pnchisqRaw(Number.MIN_VALUE, df, ncp, true, lower);
348
- if (lower ? atMin >= logTarget : Math.log1p(-atMin) <= logTarget)
571
+ // If the distribution function at the smallest positive number already passes the target, the answer is 0 (includes
572
+ // the point mass for df = 0). (For a large λ the upper tail there is built from the lower one: pnchisqBoth)
573
+ const atMin = pnchisqRaw(Number.MIN_VALUE, df, ncp, lower, true);
574
+ if (lower ? atMin >= logTarget : atMin <= logTarget)
349
575
  return 0;
350
- // Patnaik's approximation as the starting value
576
+ // Patnaik's approximation as the starting value (for a huge ν its quantile by Wilson and Hilferty's cube root)
351
577
  const c = (df + 2 * ncp) / (df + ncp);
352
- const nu = ((df + ncp) * (df + ncp)) / (df + 2 * ncp);
353
- let x0 = c * qgamma1(logTarget, nu / 2, 2, lower, true);
578
+ const nu = (df + ncp) * ((df + ncp) / (df + 2 * ncp));
579
+ let x0;
580
+ if (nu > 1e5) {
581
+ const h = 2 / (9 * nu);
582
+ x0 = c * nu * (1 - h + qnorm(logTarget, { lowerTail: lower, logP: true }) * Math.sqrt(h)) ** 3;
583
+ }
584
+ else
585
+ x0 = c * qgamma1(logTarget, nu / 2, 2, lower, true);
354
586
  if (!(x0 > 0) || !Number.isFinite(x0))
355
587
  x0 = df + ncp;
588
+ const passes = (x) => (lower ? cdf(x, true).log >= logTarget : cdf(x, false).log <= logTarget);
589
+ const narrowSpread = Math.sqrt(2 * (df + 2 * ncp)) < 1e-10 * (df + ncp);
590
+ const narrow = narrowSpread ? narrowQuantile(x0, Number.MAX_VALUE, passes) : undefined;
591
+ if (narrow !== undefined)
592
+ return narrow;
356
593
  // Bracket by doubling the upper end (the distribution function is expensive for very large x)
594
+ let lo = 0;
357
595
  let hi = Math.max(x0, df + ncp, 1);
358
- for (let i = 0; i < 2000; i++) {
359
- const v = pnchisqRaw(hi, df, ncp, lower, true);
360
- if (lower ? v >= logTarget : v <= logTarget)
361
- break;
596
+ for (let i = 0; i < 2000 && !passes(hi); i++) {
597
+ lo = hi;
362
598
  hi *= 2;
363
599
  }
364
- return invertContinuous({
600
+ const x = invertContinuous({
365
601
  logTarget,
366
602
  ...(linearTarget !== undefined && { linearTarget }),
367
603
  lower,
@@ -374,5 +610,7 @@ export function qnchisq1(p, df, ncp, lowerTail, logP) {
374
610
  lo: 0,
375
611
  hi,
376
612
  positive: true,
613
+ maxIter: 60,
377
614
  });
615
+ return confirmQuantile(x, cdf(x, lower).log, logTarget, () => searchDoubles(x, lo, hi, passes), passes);
378
616
  }