@numero-uno-jpn/rstats 0.15.0 → 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 (81) hide show
  1. package/CHANGELOG.md +48 -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-4XGKAHD3.js → chunk-3WQCKGKP.js} +2 -2
  6. package/dist/chunks/{chunk-7XHAE2LG.js → chunk-4Z2XDWKV.js} +1 -1
  7. package/dist/chunks/{chunk-QQIWOGHR.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-WEWXYHPR.js → chunk-HBMHR5SS.js} +2 -2
  11. package/dist/chunks/{chunk-HS7KIFMR.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-A3XZUJCP.js → chunk-PEYGUK32.js} +2 -2
  15. package/dist/chunks/{chunk-HNLKOICT.js → chunk-PWVQVJTP.js} +1 -1
  16. package/dist/chunks/{chunk-AEFWSUZ2.js → chunk-Q4PGYESP.js} +2 -2
  17. package/dist/chunks/{chunk-GZTLODPK.js → chunk-RCAL4VHM.js} +2 -2
  18. package/dist/chunks/{chunk-XMTYTJT6.js → chunk-SREPSVTT.js} +2 -2
  19. package/dist/chunks/chunk-UFT662QZ.js +2 -0
  20. package/dist/chunks/{chunk-CJ5ETQCK.js → chunk-VWJ74UHC.js} +2 -2
  21. package/dist/chunks/{chunk-VAPGDPHM.js → chunk-XNPU54NH.js} +1 -1
  22. package/dist/chunks/{chunk-PRDF6IU6.js → chunk-XPLDEK6D.js} +2 -2
  23. package/dist/chunks/{chunk-LWUTCYTZ.js → chunk-YGT4P7EU.js} +1 -1
  24. package/dist/chunks/{chunk-7GEYDIQC.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 +396 -60
  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/signrank.js +73 -20
  45. package/dist/distributions/t.js +48 -10
  46. package/dist/distributions/triangular.js +66 -27
  47. package/dist/distributions/tukey.js +94 -50
  48. package/dist/distributions/uniform.js +12 -9
  49. package/dist/distributions/weibull.js +43 -8
  50. package/dist/distributions.js +2 -2
  51. package/dist/internal/ddexp.d.ts +5 -0
  52. package/dist/internal/ddexp.js +28 -3
  53. package/dist/internal/discrete.js +30 -7
  54. package/dist/internal/invert.js +49 -0
  55. package/dist/internal/noncentral.d.ts +34 -0
  56. package/dist/internal/noncentral.js +115 -2
  57. package/dist/internal/poissonMixture.d.ts +7 -2
  58. package/dist/internal/poissonMixture.js +113 -32
  59. package/dist/linalg.js +2 -2
  60. package/dist/mixed.js +2 -2
  61. package/dist/numerics.js +2 -2
  62. package/dist/rstats.js +14 -14
  63. package/dist/special/dd.d.ts +1 -1
  64. package/dist/special/dd.js +4 -1
  65. package/dist/special/igam.js +93 -15
  66. package/dist/special/incbet.d.ts +10 -0
  67. package/dist/special/incbet.js +154 -48
  68. package/dist/special/incbetLargeA.js +47 -13
  69. package/dist/special/incbetPrefactor.d.ts +52 -0
  70. package/dist/special/incbetPrefactor.js +92 -0
  71. package/dist/special/incbetTemme.js +15 -3
  72. package/dist/special/loader.js +33 -7
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +2 -2
  75. package/package.json +1 -1
  76. package/dist/chunks/chunk-4EOKNOXP.js +0 -2
  77. package/dist/chunks/chunk-CMPDE3SZ.js +0 -2
  78. package/dist/chunks/chunk-LU5FHU2O.js +0 -2
  79. package/dist/chunks/chunk-LVXAWWUX.js +0 -2
  80. package/dist/chunks/chunk-NYGWVZOC.js +0 -2
  81. package/dist/chunks/chunk-VSKWQMSG.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,15 +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).
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.
13
17
  import { dt0, dt1, quantileBoundaries, smallerTail } from "../internal/dpq.js";
14
18
  import { invertContinuous } from "../internal/invert.js";
15
- 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";
16
21
  import { gammaInc } from "../special/igam.js";
17
22
  import { dpoisRaw } from "../special/loader.js";
18
- import { ddAdd, ddDiv, twoSum } from "../special/dd.js";
23
+ import { ddAdd, ddDiv, twoProd, twoSum } from "../special/dd.js";
19
24
  import { digamma } from "../special/psigamma.js";
25
+ import { lgamma1p } from "../special/gamma.js";
26
+ import { log1pmx } from "../special/log1pmx.js";
20
27
  import { dgamma1, qgamma1 } from "./gamma.js";
28
+ import { qnorm } from "./normal.js";
21
29
  function gammaKernel(a, y) {
22
30
  // For very small y the ratio y/(a+j) underflows, so keep it scaled by 2^500
23
31
  const tiny = y < 1e-250;
@@ -27,16 +35,29 @@ function gammaKernel(a, y) {
27
35
  cdf: (j, lower, log) => gammaInc(a + j, y, lower, log),
28
36
  inc: (j, log) => {
29
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
+ }
30
42
  return log ? dpoisRaw(s, y, true) + corr : dpoisRaw(s, y, false) * (1 + corr);
31
43
  },
32
44
  // d_j / d_{j-1} = y / (a + j)
33
45
  ratio: (j) => ddDiv([ys, 0], twoSum(a, j)),
34
46
  incLogDD: (j) => {
35
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]);
36
50
  return ddAdd(dpoisLogDD(s, y), [corr, 0]);
37
51
  },
38
52
  };
39
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
+ }
40
61
  /**
41
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:
42
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
@@ -53,41 +74,31 @@ function validParams(df, ncp) {
53
74
  }
54
75
  /**
55
76
  * Linear value and log of P[X <= x] (lower) / P[X > x] (x > 0 finite, ncp > 0).
56
- * 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
57
78
  */
58
79
  function pnchisqBoth(x, df, ncp, lower) {
59
80
  const mu = ncp / 2;
60
- if (mu * (x / 2) > 1e18) {
61
- // x λ is very large (far in the right tail): the peak of the series is too far away, so build the tail from the density (besselAsymptotic)
62
- const lq = upperTailAsymptotic(x, df, ncp);
63
- if (lower)
64
- return { lin: -Math.expm1(lq), log: Math.log1p(-Math.exp(lq)) };
65
- return { lin: Math.exp(lq), log: lq };
66
- }
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);
67
85
  // x so small that x/2 underflows to 0 (the smallest subnormal) is approximated by the smallest positive number
68
86
  const kernel = gammaKernel(df / 2, Math.max(x / 2, Number.MIN_VALUE));
69
- const own = mixtureCdfBoth(mu, kernel, lower);
70
- if (own.lin > 0.5) {
71
- // 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);
72
91
  let lg;
73
92
  return {
74
- lin: own.lin,
93
+ lin: 1 - p,
75
94
  get log() {
76
- lg ??= Math.log1p(-mixtureCdf(mu, kernel, !lower, false));
95
+ lg ??= Math.log1p(-p);
77
96
  return lg;
78
97
  },
79
98
  };
80
99
  }
81
- return own;
82
- }
83
- /**
84
- * log P[X > x] for very large x. Using the log-derivative of the density f, -(log f)' = s(x),
85
- * P[X > x] = f(x)/s(x) (1 + O(x^-3/2)), s(x) = 1/2 - sqrt(λ/x)/2 - (k - 3)/(4x)
86
- * (f in the form of besselAsymptotic. Used for x λ > 1e18, so the correction is negligible)
87
- */
88
- function upperTailAsymptotic(x, df, ncp) {
89
- const s = 0.5 - Math.sqrt(ncp / x) / 2 - (df - 3) / (4 * x);
90
- return besselAsymptotic(x, df, ncp, true) - Math.log(s);
100
+ // (the lower tail is likely the smaller below the mean k + λ)
101
+ return mixtureTail(mu, kernel, lower, x < df + ncp);
91
102
  }
92
103
  function pnchisqRaw(x, df, ncp, lower, log) {
93
104
  const v = pnchisqBoth(x, df, ncp, lower);
@@ -110,23 +121,101 @@ function memoCdf(df, ncp) {
110
121
  /** Core of the log density (x > 0 finite, ncp > 0) */
111
122
  function dnchisqRaw(x, df, ncp, log) {
112
123
  const a = df / 2;
113
- 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);
114
126
  const mu = ncp / 2;
115
- // 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
116
- const jStar = (-(a - 1) + Math.sqrt((a - 1) * (a - 1) + 4 * mu * y)) / 2;
117
- if (mu * y > 1e18)
127
+ const z = besselArg(x, ncp);
128
+ const method = asymptoticMethod(df, z);
129
+ if (method === "hankel")
118
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;
119
138
  // Component density y^(a+j-1) e^-y / Gamma(a+j) = d_j (a + j) / y
120
139
  return mixtureDensity(mu, gammaKernel(a, y), (j) => a + j, jStar, x, log);
121
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
+ }
122
194
  /**
123
195
  * Density for very large x λ. Apply to f(x) = exp(-(x+λ)/2) (x/λ)^(ν/2) I_ν(sqrt(λ x)) / 2 (ν = k/2 - 1) the
124
196
  * large-z asymptotic expansion of I_ν(z), e^z / sqrt(2 pi z) Σ_m (-1)^m a_m(ν) / z^m.
125
- * (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)
126
199
  */
127
- function besselAsymptotic(x, df, ncp, log) {
200
+ function besselAsymptotic(x, df, ncp, log, dGiven) {
128
201
  const nu = df / 2 - 1;
129
- const z = Math.sqrt(ncp * x);
202
+ const z = besselArg(x, ncp);
203
+ const s = besselSeries(nu, z);
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)
206
+ const rl = Math.sqrt(ncp);
207
+ const dd = dGiven ?? rootDiff(x, ncp);
208
+ const d = dd[0] + dd[1];
209
+ const [p, pe] = squareDD(dd);
210
+ const hi = -p / 2;
211
+ // (ν/2) log(x/λ) = ν log(sqrt(x)/sqrt(λ))
212
+ const rest = -Math.LN2 - pe / 2 + nu * logRootRatio(d, rl, x) - 0.5 * Math.log(2 * Math.PI * z) + Math.log(s);
213
+ if (log)
214
+ return hi + rest;
215
+ return hi > -700 ? Math.exp(hi) * Math.exp(rest) : Math.exp(hi + rest);
216
+ }
217
+ /** Σ_m (-1)^m a_m(ν) / z^m of besselAsymptotic */
218
+ function besselSeries(nu, z) {
130
219
  const mu4 = 4 * nu * nu;
131
220
  let term = 1;
132
221
  let s = 1;
@@ -136,10 +225,180 @@ function besselAsymptotic(x, df, ncp, log) {
136
225
  if (Math.abs(term) < 1e-17 * Math.abs(s))
137
226
  break;
138
227
  }
139
- // -(x + λ)/2 + z = -(sqrt(x) - sqrt(λ))^2 / 2
140
- const d = Math.sqrt(x) - Math.sqrt(ncp);
141
- const lv = -Math.LN2 - (d * d) / 2 + (nu / 2) * Math.log(x / ncp) - 0.5 * Math.log(2 * Math.PI * z) + Math.log(s);
142
- return log ? lv : Math.exp(lv);
228
+ return s;
229
+ }
230
+ /** log(sqrt(2 pi)) */
231
+ const LN_SQRT_2PI = 0.918938533204672741780329736406;
232
+ /**
233
+ * Linear value and log of P[X <= x] (lower) / P[X > x] for very large x λ, by integrating the density of
234
+ * besselAsymptotic. In t = sqrt(x) the density is g(t) = f(t²) 2t, with
235
+ * log g(t) = -(t - sqrt(λ))²/2 + (ν + 1/2) log(t / sqrt(λ)) - log sqrt(2 pi) + log S(t sqrt(λ))
236
+ * (S the series of besselSeries, 1 + O(1/(t sqrt(λ)))): close to a unit normal density whatever λ is (for k = 1 it
237
+ * is φ(t - sqrt(λ)), the term φ(t + sqrt(λ)) of the exact density being negligible). log g is concave (its second
238
+ * derivative is -1 - (ν + 1/2)/t² up to O(1/(t sqrt(λ)))), so g falls on both sides of its mode, the root of
239
+ * t² - sqrt(λ) t - (ν + 1/2) = 0. The tail beyond t0 = sqrt(x) away from the mode is the smaller one, at most about
240
+ * 1/2 (g is symmetric up to O(1/sqrt(λ))); it is integrated from t0 outwards and the other tail is 1 - (that).
241
+ * The integrand is g(t)/g(t0), which starts at 1 and decays monotonically, so the integral has full relative accuracy
242
+ * even far in a tail; log g(t0) is added in log space, with (t0 - sqrt(λ))² in double-double since in a deep tail its
243
+ * rounding would otherwise become the relative error of the probability.
244
+ */
245
+ function besselTails(x, df, ncp, lower) {
246
+ const nu = df / 2 - 1;
247
+ const c = nu + 0.5;
248
+ const rl = Math.sqrt(ncp);
249
+ const t0 = Math.sqrt(x);
250
+ // t0 - sqrt(λ) without cancellation
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;
257
+ const dir = up ? 1 : -1;
258
+ const ls0 = Math.log(besselSeries(nu, t0 * rl));
259
+ // log(g(t0 + dir u) / g(t0)), written with the offset h so that it has no cancellation near u = 0
260
+ const integrand = (u) => {
261
+ const h = dir * u;
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;
266
+ };
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)
268
+ const rate = (u) => -dir * (c / (t0 + dir * u) - (d0 + dir * u));
269
+ // Integrate over intervals of doubling width, starting from about the length over which g falls by e^-1. Since log g
270
+ // is concave, the rest beyond u is at most g(u)/rate(u); stop when that is negligible
271
+ const end = up ? Infinity : t0;
272
+ let w = 1 / (1 + Math.abs(rate(0)));
273
+ let a = 0;
274
+ let sum = 0;
275
+ const control = quadratureControl();
276
+ for (let i = 0; i < 200 && a < end; i++) {
277
+ const b = Math.min(a + w, end);
278
+ sum += kronrodAdaptive(integrand, a, b, sum, 0, control);
279
+ const r = rate(b);
280
+ if (r > 0 && integrand(b) <= 1e-17 * r * sum)
281
+ break;
282
+ a = b;
283
+ w *= 2;
284
+ }
285
+ const [p, pe] = squareDD(d0dd);
286
+ const hi = -p / 2;
287
+ const rest = -pe / 2 + c * logRootRatio(d0, rl, x) - LN_SQRT_2PI + ls0 + Math.log(sum);
288
+ const tail = hi > -700 ? Math.exp(hi) * Math.exp(rest) : Math.exp(hi + rest);
289
+ if (up !== lower)
290
+ return { lin: tail, log: hi + rest };
291
+ return { lin: 1 - tail, log: Math.log1p(-tail) };
292
+ }
293
+ /**
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.
364
+ */
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;
395
+ }
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) };
143
402
  }
144
403
  export function dnchisq1(x, df, ncp, log) {
145
404
  if (Number.isNaN(x) || Number.isNaN(df) || Number.isNaN(ncp))
@@ -160,6 +419,47 @@ export function dnchisq1(x, df, ncp, log) {
160
419
  }
161
420
  return dnchisqRaw(x, df, ncp, log);
162
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
+ }
163
463
  export function pnchisq1(q, df, ncp, lowerTail, logP) {
164
464
  if (Number.isNaN(q) || Number.isNaN(df) || Number.isNaN(ncp))
165
465
  return NaN;
@@ -211,22 +511,43 @@ export function negligibleTail(far, lowerTail, logP) {
211
511
  * Both exponents are convex in s and are smallest at u = 1 ± 2s = (k + sqrt(k² + 4qλ)) / (2q), the positive root of
212
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
213
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).
214
517
  */
215
518
  function chisqTailBound(q, df, ncp) {
216
- const u = (df + Math.sqrt(df * df + 4 * q * ncp)) / (2 * q);
217
- 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))
218
524
  return undefined;
219
- if (u > 1) {
220
- const s = (u - 1) / 2;
221
- const lb = s * q - (df / 2) * Math.log(u) - (ncp * s) / u;
222
- return lb < LOG_NEGLIGIBLE ? "lower" : undefined;
223
- }
224
- if (u < 1 && u > 0) {
225
- const s = (1 - u) / 2;
226
- const lb = -s * q - (df / 2) * Math.log(u) + (ncp * s) / u;
227
- return lb < LOG_NEGLIGIBLE ? "upper" : undefined;
228
- }
229
- 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();
230
551
  }
231
552
  export function qnchisq1(p, df, ncp, lowerTail, logP) {
232
553
  if (Number.isNaN(p) || Number.isNaN(df) || Number.isNaN(ncp))
@@ -247,34 +568,49 @@ export function qnchisq1(p, df, ncp, lowerTail, logP) {
247
568
  return qgamma1(p, df / 2, 2, lowerTail, logP);
248
569
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
249
570
  const cdf = memoCdf(df, ncp);
250
- // If the distribution function at the smallest positive number already passes the target, the answer is 0 (includes the point mass for df = 0)
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)
251
573
  const atMin = pnchisqRaw(Number.MIN_VALUE, df, ncp, lower, true);
252
574
  if (lower ? atMin >= logTarget : atMin <= logTarget)
253
575
  return 0;
254
- // 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)
255
577
  const c = (df + 2 * ncp) / (df + ncp);
256
- const nu = ((df + ncp) * (df + ncp)) / (df + 2 * ncp);
257
- 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);
258
586
  if (!(x0 > 0) || !Number.isFinite(x0))
259
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;
260
593
  // Bracket by doubling the upper end (the distribution function is expensive for very large x)
594
+ let lo = 0;
261
595
  let hi = Math.max(x0, df + ncp, 1);
262
- for (let i = 0; i < 2000; i++) {
263
- const v = pnchisqRaw(hi, df, ncp, lower, true);
264
- if (lower ? v >= logTarget : v <= logTarget)
265
- break;
596
+ for (let i = 0; i < 2000 && !passes(hi); i++) {
597
+ lo = hi;
266
598
  hi *= 2;
267
599
  }
268
- return invertContinuous({
600
+ const x = invertContinuous({
269
601
  logTarget,
270
602
  ...(linearTarget !== undefined && { linearTarget }),
271
603
  lower,
272
604
  cdf: (x, l) => cdf(x, l).lin,
273
605
  cdfLog: (x, l) => cdf(x, l).log,
274
606
  pdfLog: (x) => dnchisqRaw(x, df, ncp, true),
275
- x0: Math.min(x0, hi),
607
+ // Start just inside the bracket when the first upper end already passes the target: a start at the end itself
608
+ // falls back to bisection towards 0, through x where the series is slow (seconds for λ = 1e12)
609
+ x0: x0 < hi ? x0 : hi * (1 - 2 ** -26),
276
610
  lo: 0,
277
611
  hi,
278
612
  positive: true,
613
+ maxIter: 60,
279
614
  });
615
+ return confirmQuantile(x, cdf(x, lower).log, logTarget, () => searchDoubles(x, lo, hi, passes), passes);
280
616
  }