@numero-uno-jpn/rstats 0.15.2 → 0.16.0

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 (297) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +35 -5
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +87 -8
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +11 -1
  52. package/dist/distributions/f.js +73 -22
  53. package/dist/distributions/gamma.js +61 -6
  54. package/dist/distributions/geometric.js +53 -14
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +6 -1
  58. package/dist/distributions/kumaraswamy.js +22 -4
  59. package/dist/distributions/laplace.js +31 -7
  60. package/dist/distributions/logistic.js +11 -2
  61. package/dist/distributions/lognormal.js +20 -3
  62. package/dist/distributions/multinomial.js +54 -11
  63. package/dist/distributions/nbeta.js +128 -35
  64. package/dist/distributions/nchisq.js +85 -14
  65. package/dist/distributions/negbinomial.js +100 -18
  66. package/dist/distributions/normal.js +35 -5
  67. package/dist/distributions/nt.d.ts +28 -3
  68. package/dist/distributions/nt.js +536 -35
  69. package/dist/distributions/pareto.js +9 -1
  70. package/dist/distributions/poisson.js +28 -3
  71. package/dist/distributions/signrank.js +7 -4
  72. package/dist/distributions/summary.js +450 -60
  73. package/dist/distributions/t.js +55 -3
  74. package/dist/distributions/triangular.js +45 -13
  75. package/dist/distributions/tukey.js +21 -2
  76. package/dist/distributions/uniform.js +2 -0
  77. package/dist/distributions/weibull.js +33 -3
  78. package/dist/distributions/wilcox.d.ts +9 -3
  79. package/dist/distributions/wilcox.js +155 -26
  80. package/dist/distributions.js +2 -2
  81. package/dist/htest/agreement.d.ts +3 -2
  82. package/dist/htest/agreement.js +76 -14
  83. package/dist/htest/ansariTest.d.ts +6 -1
  84. package/dist/htest/ansariTest.js +75 -8
  85. package/dist/htest/aov.d.ts +1 -1
  86. package/dist/htest/aov.js +48 -34
  87. package/dist/htest/binomTest.d.ts +5 -0
  88. package/dist/htest/binomTest.js +41 -17
  89. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  90. package/dist/htest/brunnerMunzelTest.js +7 -5
  91. package/dist/htest/chisqTest.d.ts +2 -1
  92. package/dist/htest/chisqTest.js +130 -43
  93. package/dist/htest/cor.d.ts +2 -1
  94. package/dist/htest/cor.js +17 -19
  95. package/dist/htest/core/ansari.d.ts +9 -0
  96. package/dist/htest/core/ansari.js +21 -1
  97. package/dist/htest/core/kolmogorov.d.ts +25 -0
  98. package/dist/htest/core/kolmogorov.js +123 -0
  99. package/dist/htest/core/mantelhaen.js +6 -4
  100. package/dist/htest/core/shapiro.d.ts +1 -1
  101. package/dist/htest/core/shapiro.js +5 -1
  102. package/dist/htest/dunnett.js +14 -5
  103. package/dist/htest/effectSize.d.ts +2 -0
  104. package/dist/htest/effectSize.js +91 -29
  105. package/dist/htest/fisherTest.d.ts +2 -2
  106. package/dist/htest/fisherTest.js +36 -18
  107. package/dist/htest/groups.d.ts +7 -0
  108. package/dist/htest/groups.js +21 -4
  109. package/dist/htest/ksTest.d.ts +3 -1
  110. package/dist/htest/ksTest.js +23 -2
  111. package/dist/htest/leveneTest.js +19 -3
  112. package/dist/htest/mantelhaenTest.js +125 -25
  113. package/dist/htest/mcnemarTest.js +32 -11
  114. package/dist/htest/multipleComparisons.d.ts +8 -1
  115. package/dist/htest/multipleComparisons.js +44 -21
  116. package/dist/htest/normalityTests.js +44 -10
  117. package/dist/htest/onewayTest.js +96 -5
  118. package/dist/htest/pAdjust.d.ts +3 -2
  119. package/dist/htest/pAdjust.js +38 -6
  120. package/dist/htest/pairwise.d.ts +1 -1
  121. package/dist/htest/pairwise.js +17 -15
  122. package/dist/htest/poissonTest.d.ts +1 -1
  123. package/dist/htest/poissonTest.js +111 -59
  124. package/dist/htest/polycor.js +27 -7
  125. package/dist/htest/power.d.ts +11 -1
  126. package/dist/htest/power.js +112 -8
  127. package/dist/htest/propTest.js +21 -4
  128. package/dist/htest/pwr.js +121 -24
  129. package/dist/htest/rankTests.js +29 -5
  130. package/dist/htest/tTest.js +44 -21
  131. package/dist/htest/trendTests.d.ts +7 -3
  132. package/dist/htest/trendTests.js +114 -20
  133. package/dist/htest/types.d.ts +5 -0
  134. package/dist/htest/types.js +7 -0
  135. package/dist/htest/varTest.js +45 -14
  136. package/dist/htest/wilcoxTest.js +114 -21
  137. package/dist/integrate/quadpack.js +27 -5
  138. package/dist/internal/covmat.d.ts +5 -0
  139. package/dist/internal/covmat.js +20 -0
  140. package/dist/internal/ddexp.d.ts +23 -1
  141. package/dist/internal/ddexp.js +86 -6
  142. package/dist/internal/discrete.d.ts +14 -0
  143. package/dist/internal/discrete.js +78 -5
  144. package/dist/internal/extremes.d.ts +9 -0
  145. package/dist/internal/extremes.js +24 -0
  146. package/dist/internal/fround.js +13 -4
  147. package/dist/internal/integer.d.ts +9 -0
  148. package/dist/internal/integer.js +12 -0
  149. package/dist/internal/invert.d.ts +5 -0
  150. package/dist/internal/invert.js +25 -7
  151. package/dist/internal/noncentral.d.ts +7 -0
  152. package/dist/internal/noncentral.js +9 -0
  153. package/dist/internal/poissonMixture.js +29 -6
  154. package/dist/internal/scaledInverse.d.ts +10 -0
  155. package/dist/internal/scaledInverse.js +22 -0
  156. package/dist/internal/seq.js +15 -2
  157. package/dist/internal/summary.d.ts +90 -0
  158. package/dist/internal/summary.js +458 -39
  159. package/dist/internal/uniroot.d.ts +7 -0
  160. package/dist/internal/uniroot.js +28 -3
  161. package/dist/linalg/basic.d.ts +3 -1
  162. package/dist/linalg/basic.js +51 -7
  163. package/dist/linalg/chol.js +4 -1
  164. package/dist/linalg/dot.d.ts +29 -0
  165. package/dist/linalg/dot.js +132 -0
  166. package/dist/linalg/eigen.d.ts +6 -1
  167. package/dist/linalg/eigen.js +71 -14
  168. package/dist/linalg/expm.d.ts +3 -2
  169. package/dist/linalg/expm.js +109 -15
  170. package/dist/linalg/kappa.js +58 -10
  171. package/dist/linalg/lu.d.ts +2 -1
  172. package/dist/linalg/lu.js +35 -5
  173. package/dist/linalg/matrix.d.ts +14 -0
  174. package/dist/linalg/matrix.js +24 -0
  175. package/dist/linalg/ops.js +60 -13
  176. package/dist/linalg/qr.d.ts +2 -1
  177. package/dist/linalg/qr.js +91 -23
  178. package/dist/linalg/schur.js +11 -3
  179. package/dist/linalg/solve.d.ts +6 -1
  180. package/dist/linalg/solve.js +147 -26
  181. package/dist/linalg/svd.d.ts +9 -2
  182. package/dist/linalg/svd.js +29 -11
  183. package/dist/linalg.js +2 -2
  184. package/dist/mixed.js +4 -4
  185. package/dist/models/anovaSequential.d.ts +16 -1
  186. package/dist/models/anovaSequential.js +124 -25
  187. package/dist/models/aovEz.js +140 -30
  188. package/dist/models/aovStrata.js +55 -22
  189. package/dist/models/carAnova.d.ts +1 -1
  190. package/dist/models/carAnova.js +83 -32
  191. package/dist/models/coxph.js +148 -66
  192. package/dist/models/estimable.d.ts +15 -0
  193. package/dist/models/estimable.js +68 -0
  194. package/dist/models/formula.d.ts +1 -1
  195. package/dist/models/formula.js +26 -8
  196. package/dist/models/glm.d.ts +35 -5
  197. package/dist/models/glm.js +398 -55
  198. package/dist/models/glmAnova.js +84 -13
  199. package/dist/models/glmConfint.d.ts +1 -1
  200. package/dist/models/glmConfint.js +115 -27
  201. package/dist/models/glmFamily.d.ts +10 -0
  202. package/dist/models/glmFamily.js +244 -40
  203. package/dist/models/lm.d.ts +12 -1
  204. package/dist/models/lm.js +235 -36
  205. package/dist/models/lmer.d.ts +20 -1
  206. package/dist/models/lmer.js +109 -27
  207. package/dist/models/lmerAnova.js +37 -4
  208. package/dist/models/lmerHypotheses.d.ts +6 -2
  209. package/dist/models/lmerHypotheses.js +14 -2
  210. package/dist/models/lmerTest.d.ts +9 -2
  211. package/dist/models/lmerTest.js +64 -19
  212. package/dist/models/mauchly.d.ts +4 -1
  213. package/dist/models/mauchly.js +34 -13
  214. package/dist/models/mixedStructure.js +6 -0
  215. package/dist/models/modelFrame.js +8 -2
  216. package/dist/models/modelMatrix.d.ts +3 -1
  217. package/dist/models/modelMatrix.js +40 -15
  218. package/dist/models/scaledTables.d.ts +8 -0
  219. package/dist/models/scaledTables.js +6 -0
  220. package/dist/models/survival.d.ts +6 -1
  221. package/dist/models/survival.js +67 -27
  222. package/dist/models/tiedTimes.d.ts +2 -0
  223. package/dist/models/tiedTimes.js +34 -0
  224. package/dist/numerics/deriv.d.ts +1 -1
  225. package/dist/numerics/deriv.js +64 -8
  226. package/dist/numerics/integrate.d.ts +9 -1
  227. package/dist/numerics/integrate.js +103 -16
  228. package/dist/numerics/interp.d.ts +8 -2
  229. package/dist/numerics/interp.js +352 -50
  230. package/dist/numerics/ode.js +55 -1
  231. package/dist/numerics.js +2 -2
  232. package/dist/optim/localmin.js +4 -0
  233. package/dist/optim/optim.d.ts +3 -1
  234. package/dist/optim/optim.js +80 -8
  235. package/dist/random/beta.js +53 -4
  236. package/dist/random/binomial.d.ts +14 -3
  237. package/dist/random/binomial.js +59 -24
  238. package/dist/random/continuous.js +33 -5
  239. package/dist/random/extra.js +42 -9
  240. package/dist/random/gamma.d.ts +4 -1
  241. package/dist/random/gamma.js +36 -8
  242. package/dist/random/hyper.js +9 -6
  243. package/dist/random/mt.js +17 -2
  244. package/dist/random/poisson.js +26 -3
  245. package/dist/random/r2dtable.d.ts +8 -1
  246. package/dist/random/r2dtable.js +24 -3
  247. package/dist/random/rank.d.ts +2 -0
  248. package/dist/random/rank.js +44 -4
  249. package/dist/random/sample.d.ts +12 -2
  250. package/dist/random/sample.js +57 -20
  251. package/dist/random/streams.js +4 -2
  252. package/dist/rstats.js +14 -14
  253. package/dist/special/besselIK.d.ts +12 -0
  254. package/dist/special/besselIK.js +168 -23
  255. package/dist/special/besselJY.d.ts +11 -1
  256. package/dist/special/besselJY.js +127 -19
  257. package/dist/special/besselSeries.d.ts +27 -0
  258. package/dist/special/besselSeries.js +45 -2
  259. package/dist/special/beta.js +11 -1
  260. package/dist/special/choose.js +17 -8
  261. package/dist/special/dd.js +122 -18
  262. package/dist/special/extra.js +14 -2
  263. package/dist/special/gamma.js +15 -2
  264. package/dist/special/igam.js +33 -6
  265. package/dist/special/incbet.js +100 -10
  266. package/dist/special/incbetLargeA.js +7 -2
  267. package/dist/special/incbetPrefactor.d.ts +5 -0
  268. package/dist/special/incbetPrefactor.js +14 -3
  269. package/dist/special/incbetTemme.d.ts +7 -0
  270. package/dist/special/incbetTemme.js +45 -12
  271. package/dist/special/loader.d.ts +1 -1
  272. package/dist/special/loader.js +179 -33
  273. package/dist/special/log1pmx.js +4 -0
  274. package/dist/special.js +2 -2
  275. package/dist/tests.js +11 -11
  276. package/llms.txt +12 -6
  277. package/package.json +1 -1
  278. package/dist/chunks/chunk-2CUKVVRO.js +0 -2
  279. package/dist/chunks/chunk-3WQCKGKP.js +0 -2
  280. package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
  281. package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
  282. package/dist/chunks/chunk-D4F7GQAY.js +0 -2
  283. package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
  284. package/dist/chunks/chunk-HBMHR5SS.js +0 -2
  285. package/dist/chunks/chunk-IBPWRQIF.js +0 -2
  286. package/dist/chunks/chunk-JLAH3X77.js +0 -2
  287. package/dist/chunks/chunk-LG74QY5U.js +0 -2
  288. package/dist/chunks/chunk-PEYGUK32.js +0 -2
  289. package/dist/chunks/chunk-Q4PGYESP.js +0 -2
  290. package/dist/chunks/chunk-RCAL4VHM.js +0 -3
  291. package/dist/chunks/chunk-SREPSVTT.js +0 -2
  292. package/dist/chunks/chunk-UFT662QZ.js +0 -2
  293. package/dist/chunks/chunk-VWJ74UHC.js +0 -2
  294. package/dist/chunks/chunk-XNPU54NH.js +0 -2
  295. package/dist/chunks/chunk-XPLDEK6D.js +0 -2
  296. package/dist/chunks/chunk-YGT4P7EU.js +0 -2
  297. package/dist/chunks/chunk-YVREYVI2.js +0 -2
@@ -24,6 +24,11 @@
24
24
  // the rounding (laplace); for a small ν (a < 1e-5) formula B is used at any t, and a t so near 0 that P is Φ(-δ) to
25
25
  // the double is given that value (nearZero). The smaller tail is computed, the larger is 1 - (smaller).
26
26
  //
27
+ // Far tails of a large δ (a log beyond about 1e9, or |δ| > 2^32), where the logs of the integrand in double precision
28
+ // no longer place its peak: Laplace's method with the derivatives scaled and t S - δ in double-double (laplaceWide),
29
+ // the trapezoidal sum with the logs in double-double where the expansion is not accurate enough, the integral of the
30
+ // ratio to Φ(-δ) where the peak is broad (integrateShifted), and for t >> sqrt(ν) an expansion over Z (zTail).
31
+ //
27
32
  // For accuracy, the node w and, on top of it, e^(w/2), the exponent a (e^w - 1 - w) and the normal argument
28
33
  // t S - δ are formed in double-double (rounding in each is amplified hundreds of times in the tails). Nodes
29
34
  // where the rounding effect is estimated to be at most eps times the peak value are computed in double
@@ -35,7 +40,8 @@ import { erfcxNonNegative } from "../special/erf.js";
35
40
  import { gammaInc } from "../special/igam.js";
36
41
  import { dpoisRaw, stirlerr } from "../special/loader.js";
37
42
  import { lgamma1p } from "../special/gamma.js";
38
- import { pnorm, qnorm } from "./normal.js";
43
+ import { qgammaStd } from "./gamma.js";
44
+ import { dnorm, pnorm, qnorm } from "./normal.js";
39
45
  const LN_SQRT_2PI = 0.918938533204672741780329736406;
40
46
  const SQRT_2_PI = 0.7978845608028654; // sqrt(2/pi)
41
47
  const LN2_DD = [0.6931471805599453, 2.3190468138462996e-17];
@@ -103,11 +109,27 @@ function shapeTimesExp(a, w) {
103
109
  */
104
110
  function gammaLog(a, w, lower) {
105
111
  const x = shapeTimesExp(a, w);
106
- if (x > X_TINY)
112
+ if (x > X_TINY) {
113
+ // Q(a, x) = (a/A_SUB) Q(A_SUB, x) (1 + O(A_SUB log x)) for a < A_SUB: at a subnormal a the log of Q, itself near a,
114
+ // lost digits (7e-5 at a = 1e-320)
115
+ if (!lower && a < A_SUB)
116
+ return [gammaInc(A_SUB, x, false, true) + Math.log(a / A_SUB), dpoisRaw(a, x, true)];
107
117
  return [gammaInc(a, x, lower, true), dpoisRaw(a, x, true)];
108
- const lp = a * (Math.log(a) + w) - lgamma1p(a);
109
- return [lower ? lp : lp > -Math.LN2 ? Math.log(-Math.expm1(lp)) : Math.log1p(-Math.exp(lp)), lp];
118
+ }
119
+ // log P = a m, m = log x - lgamma1p(a)/a; lgamma1p(a)/a is -γ (1 + O(a)) where lgamma1p(a) would be subnormal
120
+ const m = Math.log(a) + w - (a < A_SUB ? -EULER : lgamma1p(a) / a);
121
+ const lp = a * m;
122
+ if (lower)
123
+ return [lp, lp];
124
+ // log Q = log(-expm1(a m)): log(a) + log(-m) + log1p(lp/2) where a m is so small (it may be subnormal)
125
+ const lq = lp > -1e-10 ? Math.log(a) + Math.log(-m) + Math.log1p(lp / 2) : lp > -Math.LN2 ? Math.log(-Math.expm1(lp)) : Math.log1p(-Math.exp(lp));
126
+ return [lq, lp];
110
127
  }
128
+ /** Below this a the upper incomplete gamma function is scaled from Q(A_SUB, x) (gammaLog) */
129
+ const A_SUB = 1e-300;
130
+ const EULER = 0.5772156649015329;
131
+ /** Above this x/(a + 1) the second derivative of log Q(a, x) in w comes from the asymptotic series of Q (logIntegrand) */
132
+ const Q_ASYMPTOTIC = 1e8;
111
133
  /** Log of the integrand (double precision, for locating the peak) and its first and second derivatives */
112
134
  function logIntegrand(pr, w) {
113
135
  const { a, t, delta } = pr;
@@ -121,24 +143,43 @@ function logIntegrand(pr, w) {
121
143
  const x = shapeTimesExp(a, w);
122
144
  const upperG = pr.kind === "cdfQ";
123
145
  const [lG, ld] = gammaLog(a, w, !upperG);
124
- const xf = a * Math.exp(ld - lG); // x f(x) / G
146
+ // x f(x) / G (with log a inside the exp: for a subnormal a, f(x)/G alone can overflow)
147
+ const xf = Math.exp(Math.log(a) + ld - lG);
125
148
  const sgn = upperG ? -1 : 1;
126
149
  const L = Math.log(t / 2) + w / 2 - 0.5 * z * z - LN_SQRT_2PI + lG;
127
150
  const d1 = 0.5 - (z * tS) / 2 + sgn * xf;
128
- const d2 = -(tS * tS) / 4 - (z * tS) / 4 + sgn * xf * (a - x) - xf * xf;
151
+ // (for Q, the derivative of -xf is xf (x - a - xf), which cancels where x is large: xf = x/(1 + (a-1)/x + ...),
152
+ // from logs near -x, is off by about eps x relative, the difference by eps x² against its value of about -1. From
153
+ // the asymptotic series of Q, x - a - xf = -1 - (a-1)/x up to O(((a+1)/x)²); with the cancelled form the peak
154
+ // search of formula B for a subnormal a and δ = 1e5 stopped short in steps of 1/x, and the log of pt was +Infinity)
155
+ const d2G = upperG && x > Q_ASYMPTOTIC * (a + 1) ? -xf * (1 + (a - 1) / x) : sgn * xf * (a - x) - xf * xf;
156
+ const d2 = -(tS * tS) / 4 - (z * tS) / 4 + d2G;
129
157
  return [L, d1, d2];
130
158
  }
131
159
  let L = pr.logC - a * m;
132
160
  let d1 = -a * Math.expm1(w);
133
161
  let d2 = -a * ew;
162
+ if (pr.shift !== undefined && w > 700) {
163
+ // (a e^w from its log, where e^w overflows: for a subnormal a the peak of integrateShifted is near w = 723)
164
+ const aew = Math.exp(Math.log(a) + w);
165
+ L = pr.logC - (aew - a * (1 + w));
166
+ d1 = -(aew - a);
167
+ d2 = -aew;
168
+ }
134
169
  if (pr.kind === "cdf") {
135
170
  const r = millsInv(z);
136
- L += pnorm(z, { logP: true });
171
+ if (pr.complement) {
172
+ // log |ρ - 1| and its derivative (the second is left to bracketedPeak)
173
+ const lr = logPhiRatio(tS, delta);
174
+ // (e^lr / (e^lr - 1) is 1 where both overflow)
175
+ return [L + logAbsExpm1(lr), d1 + (tS / 2) * r * (lr > 40 ? 1 : Math.exp(lr) / Math.expm1(lr)), NaN];
176
+ }
177
+ L += pr.shift === undefined ? pnorm(z, { logP: true }) : logPhiRatio(tS, delta);
137
178
  d1 += (tS / 2) * r;
138
179
  d2 += (tS / 4) * r - (tS / 2) * (tS / 2) * r * (z + r);
139
180
  }
140
181
  else {
141
- L += w / 2 - 0.5 * z * z - LN_SQRT_2PI;
182
+ L += pr.shift === undefined ? w / 2 - 0.5 * z * z - LN_SQRT_2PI : w / 2 + tS * (delta - tS / 2);
142
183
  d1 += 0.5 - (z * tS) / 2;
143
184
  d2 += -(tS * tS) / 4 - (z * tS) / 4;
144
185
  }
@@ -184,8 +225,9 @@ function logPhiDD(zd) {
184
225
  const corr = zd[1] * millsInv(z);
185
226
  if (z > -5)
186
227
  return twoSum(pnorm(z, { logP: true }), corr);
187
- const zz = ddMul(zd, zd);
188
- return ddAdd([-zz[0] / 2, -zz[1] / 2], [Math.log(0.5 * erfcxNonNegative(-z * Math.SQRT1_2)), 0]);
228
+ // (z²/2 as z (z/2), the same to the bit: z² alone overflows from |z| = 1.34e154, z²/2 from 1.9e154)
229
+ const zh = ddMul(zd, [zd[0] / 2, zd[1] / 2]);
230
+ return ddAdd([-zh[0], -zh[1]], [Math.log(0.5 * erfcxNonNegative(-z * Math.SQRT1_2)), 0]);
189
231
  }
190
232
  /**
191
233
  * Value of the integrand at node w (double-double). If log, return the log in double-double
@@ -231,11 +273,23 @@ function integrand(pr, w, log, peak = Infinity) {
231
273
  const g = x > X_TINY ? gammaInc(a, x, lower, false) : Math.exp(gammaLog(a, w[0] + w[1], lower)[0]);
232
274
  return [(t / 2) * (S[0] + S[1]) * Math.exp(-0.5 * zz[0] - LN_SQRT_2PI) * (1 - zz[1] / 2) * g, 0];
233
275
  }
234
- // a (e^w - 1 - w); (a tiny a reaches e^w near the overflow threshold, where the splitting in ddMulNum overflows)
276
+ // a (e^w - 1 - w); (a tiny a reaches e^w near the overflow threshold, where the splitting in ddMulNum overflows;
277
+ // in integrateShifted beyond it, from the log of a e^w)
235
278
  const m = expm1mx(w, ew);
236
- const E = m[0] < 1e290 ? ddMulNum(m, a) : twoSum(a * m[0], a * m[1]);
279
+ const E = pr.shift !== undefined && w[0] > 700
280
+ ? twoSum(Math.exp(Math.log(a) + w[0] + w[1]), -a * (1 + w[0]))
281
+ : m[0] < 1e290
282
+ ? ddMulNum(m, a)
283
+ : twoSum(a * m[0], a * m[1]);
237
284
  if (!(E[0] < Infinity))
238
285
  return [log ? -Infinity : 0, 0];
286
+ if (pr.shift !== undefined) {
287
+ // (integrateShifted: the log less log Φ(-δ) or log φ(δ), of a moderate size)
288
+ const y = ddMulNum(S, t)[0];
289
+ const lr = pr.kind === "cdf" ? logPhiRatio(y, delta) : y * (delta - y / 2);
290
+ const l = ddAdd([pr.logC - E[0], -E[1]], [pr.complement ? logAbsExpm1(lr) : lr, 0]);
291
+ return pr.kind === "cdf" ? l : ddAdd(l, [w[0] / 2, w[1] / 2]);
292
+ }
239
293
  const zd = ddAdd(ddMulNum(S, t), [-delta, 0]);
240
294
  const z = zd[0];
241
295
  if (pr.kind === "cdf") {
@@ -257,7 +311,7 @@ function integrand(pr, w, log, peak = Infinity) {
257
311
  return [Math.exp(lv) * (1 - E[1] - zz[1] / 2) * (S[0] + S[1]), 0];
258
312
  }
259
313
  /** Trapezoidal sum (step h in z, extending both ways until negligible) */
260
- function trapezoid(pr, w0, sigma, h, log, offset, odd, peak) {
314
+ function trapezoid(pr, w0, sigma, h, log, offset, odd, peak, offsetLow) {
261
315
  // If odd, only the odd-indexed nodes (the points added by halving the step)
262
316
  let sum = 0;
263
317
  const node = (z) => {
@@ -266,6 +320,8 @@ function trapezoid(pr, w0, sigma, h, log, offset, odd, peak) {
266
320
  const d = (sigma / 2) * (z - Math.expm1(-z));
267
321
  const v = integrand(pr, twoSum(w0, d), log, peak);
268
322
  const jac = (sigma / 2) * (1 + ez);
323
+ if (offsetLow !== undefined)
324
+ return Math.exp(v[0] - offset + (v[1] - offsetLow)) * jac;
269
325
  return log ? Math.exp(v[0] - offset) * (1 + v[1]) * jac : v[0] * jac;
270
326
  };
271
327
  const start = odd ? 1 : 0;
@@ -294,11 +350,31 @@ function trapezoid(pr, w0, sigma, h, log, offset, odd, peak) {
294
350
  return sum;
295
351
  }
296
352
  function integrate(pr, needLog) {
353
+ // Far tails of a large δ (LOG_LARGE, D_LARGE): over z for a large t (zTail; the density is symmetric under
354
+ // (t, δ) -> (-t, -δ), and for the distribution function a negative δ is the upper tail), otherwise laplaceWide below
355
+ const large = farLogEstimate(pr) > LOG_LARGE || Math.abs(pr.delta) > D_LARGE;
356
+ if (large && pr.t * pr.delta > 0 && Math.abs(pr.t) / Math.sqrt(2 * pr.a) >= T_Z) {
357
+ return zTail(pr.a, Math.abs(pr.t), Math.abs(pr.delta), pr.kind === "pdf" ? "pdf" : pr.delta > 0 ? "lower" : "upper");
358
+ }
297
359
  if (pr.a > A_LAPLACE) {
298
360
  const v = laplace(pr);
299
361
  if (v !== undefined)
300
362
  return v;
301
363
  }
364
+ // (for the distribution function a negative δ here is the upper tail near 1, whose logs are of a moderate size)
365
+ if (large && !(pr.kind === "cdf" && pr.delta < 0)) {
366
+ const sharp = { w: NaN, sigma: NaN };
367
+ const v = laplaceWide(pr, sharp);
368
+ if (v !== undefined)
369
+ return v;
370
+ // A sharp peak (L'' <= -1e5) where the expansion is not accurate enough (u at the peak is of order -10: log Φ(u)
371
+ // is not yet nearly quadratic): its log there is at most about 1e17 (beyond, the expansion's error is below the
372
+ // rounding), so the trapezoidal sum with the logs of the nodes and of the peak in double-double resolves it. A
373
+ // broad peak: integrateShifted
374
+ if (!Number.isNaN(sharp.w))
375
+ return integrateCore(pr, true, { w: sharp.w, sigma: sharp.sigma, L: NaN }, true);
376
+ return integrateShifted(pr);
377
+ }
302
378
  if (pr.kind === "cdf") {
303
379
  // (for a tiny a the density of w is spread over w down to about -1/a, and the peak of formula A is not found;
304
380
  // formula B is used at any t)
@@ -332,6 +408,20 @@ function integrate(pr, needLog) {
332
408
  }
333
409
  return integrateCore(pr, needLog);
334
410
  }
411
+ /**
412
+ * -log of the far tail (cdf, δ > 0 and t below it) or of the density far from the centre, roughly: the minimum over
413
+ * S of (t S - δ)²/2 + a S², δ²/2 / (1 + t²/(2a)) for t δ > 0, and δ²/2 otherwise (within a factor of about 2 where
414
+ * it is large). The peak of the integrand itself (findPeak) is no guide: where Φ(t S - δ) is a steep step, formula A's
415
+ * peak is not found, and its value can be that of a node far in the left tail of Φ
416
+ */
417
+ function farLogEstimate(pr) {
418
+ const { a, t, delta, kind } = pr;
419
+ if (kind === "cdf" && !(delta > 0))
420
+ return 0;
421
+ const d = Math.abs(delta);
422
+ const h = t * delta > 0 ? d / Math.hypot(1, t / Math.sqrt(2 * a)) : d;
423
+ return (h * h) / 2;
424
+ }
335
425
  /**
336
426
  * Below this a, formula B is used at any t: the peak of formula A is not found for a below about 1e-15, and from
337
427
  * 1e-5 down its error reaches 5e-15 of P, where formula B, a correction of order a log(t²/a) to Φ(-δ), keeps 1e-16
@@ -446,6 +536,9 @@ function laplace(pr) {
446
536
  const ew = Math.exp(w);
447
537
  if (!(w > -1390 && L2 >= 1e5))
448
538
  return undefined;
539
+ // (the peak beyond the bracket, for a large δ: pt(1e9, 1e6, ncp 1e20) was -3.9e38, its log is -5e27; laplaceWide)
540
+ if (p.d1 > 0 && 50 - w < 1e-9)
541
+ return undefined;
449
542
  const r3 = (-a * ew + f[2]) / L2;
450
543
  const r4 = (-a * ew + f[3]) / L2;
451
544
  const c1 = r4 / L2 / 8 + (5 * r3 * r3) / L2 / 24;
@@ -472,6 +565,282 @@ function laplace(pr) {
472
565
  const q = cdf ? Math.abs(v) / 2 / (Math.sqrt(L2) * Math.max(1, -u)) : 0;
473
566
  return 1 / (L2 * L2) + q ** 6 <= 1e-17 * Math.max(1, Math.abs(value.log)) ? value : undefined;
474
567
  }
568
+ /**
569
+ * laplace where the log of the integrand is beyond LOG_LARGE (a large δ, at any a): there the peak can lie beyond
570
+ * w = 50 (S* is about t δ/(t² + 2a) for t > 0), and v = t S, v² and a e^w can overflow while the answer is finite. The
571
+ * derivatives d1, L2 and f are formed in units of 2^(2k), with 2^k about max(|v|, sqrt(a e^w)) / 2^400, and u from v
572
+ * in double-double (where t² >> a, u = v - δ is a small part of δ)
573
+ */
574
+ function laplaceWide(pr, sharp) {
575
+ const { a, t, delta, kind } = pr;
576
+ const cdf = kind === "cdf";
577
+ const la = Math.log(a);
578
+ const at = (w) => {
579
+ const lg2 = Math.max(Math.log2(Math.abs(t)) + w / 2 / Math.LN2, (la + w) / 2 / Math.LN2);
580
+ const k = Math.max(0, Math.ceil(lg2) - 400);
581
+ // (beyond the double range of v the derivatives are not formed: the peak is below there)
582
+ if (lg2 > 1100) {
583
+ const f = [NaN, NaN, NaN, NaN];
584
+ return { u: NaN, v: NaN, vs: NaN, sk: 1, k, f, d1: NaN, L2: NaN, aew: NaN };
585
+ }
586
+ const sk = 2 ** -k;
587
+ const vs = t * Math.exp(w / 2 - k * Math.LN2);
588
+ const v = vs / sk;
589
+ const u = Math.abs(w) < 1 ? t - delta + t * Math.expm1(w / 2) : v - delta;
590
+ // a e^w 2^-2k (from its log where e^w overflows: a subnormal a puts the peak near w = 735)
591
+ const direct = k === 0 && w < 700;
592
+ const aew = direct ? a * Math.exp(w) : Math.exp(la + w - 2 * k * Math.LN2);
593
+ const v2 = vs * vs;
594
+ let f;
595
+ if (cdf) {
596
+ const [l1, l2, l3, l4] = logPhiDerivs(u);
597
+ const l1v = l1 * sk * vs;
598
+ const l3v = (l3 / sk) * vs;
599
+ const l4v2 = (((l4 / sk) * vs) / sk) * vs;
600
+ f = [
601
+ l1v / 2,
602
+ (l2 * v2 + l1v) / 4,
603
+ (l3v * v2 + 3 * l2 * v2 + l1v) / 8,
604
+ (l4v2 * v2 + 6 * l3v * v2 + 7 * l2 * v2 + l1v) / 16,
605
+ ];
606
+ }
607
+ else {
608
+ const uv = u * sk * vs;
609
+ f = [0.5 * sk * sk - uv / 2, -(v2 + uv) / 4, -(3 * v2 + uv) / 8, -(7 * v2 + uv) / 16];
610
+ }
611
+ const d1 = (direct ? -a * Math.expm1(w) : -(aew - a * sk * sk)) + f[0];
612
+ return { u, v, vs, sk, k, f, d1, L2: aew - f[1], aew };
613
+ };
614
+ // w*: as in laplace, over w up to 1418 (e^(w/2) up to the overflow threshold), from the estimate of the peak; a d1
615
+ // that is not formed (beyond the double range) moves the upper end down. Where L' is about -a e^w Newton's steps are
616
+ // about 1 long, so a step that does not halve the one before last is replaced by bisection (as in rtsafe)
617
+ let lo = -1400;
618
+ let hi = 1418;
619
+ let w = 0;
620
+ if (t > 0 && delta > 0) {
621
+ const w0 = 2 * Math.log(delta / (t + (2 * a) / t));
622
+ if (w0 > lo && w0 < hi)
623
+ w = w0;
624
+ }
625
+ let p = at(w);
626
+ let dx = hi - lo;
627
+ let dxOld = dx;
628
+ for (let i = 0; i < 400 && hi - lo > 4e-16 * Math.max(1, Math.abs(w)); i++) {
629
+ if (Number.isNaN(p.d1) || Number.isNaN(p.L2)) {
630
+ hi = w;
631
+ w = (lo + hi) / 2;
632
+ p = at(w);
633
+ continue;
634
+ }
635
+ const step = p.d1 / p.L2;
636
+ if ((Math.abs(step) * Math.sqrt(p.L2)) / p.sk < 1e-9)
637
+ break;
638
+ if (p.d1 > 0)
639
+ lo = w;
640
+ else if (p.d1 < 0)
641
+ hi = w;
642
+ else
643
+ break;
644
+ const next = w + step;
645
+ if (next > lo && next < hi && Math.abs(2 * step) <= Math.abs(dxOld)) {
646
+ dxOld = dx;
647
+ dx = step;
648
+ w = next;
649
+ }
650
+ else {
651
+ dxOld = dx;
652
+ dx = (hi - lo) / 2;
653
+ w = lo + dx;
654
+ }
655
+ p = at(w);
656
+ }
657
+ const { u, vs, sk, k, f, L2, aew } = p;
658
+ if (!(w > -1390 && (k > 0 || L2 >= 1e5)) || !Number.isFinite(L2))
659
+ return undefined;
660
+ // (the peak, for the trapezoidal sum where the expansion is not accurate enough)
661
+ sharp.w = w;
662
+ sharp.sigma = Math.min(sk / Math.sqrt(L2), 10);
663
+ const r3 = (-aew + f[2]) / L2;
664
+ const r4 = (-aew + f[3]) / L2;
665
+ const c1 = ((r4 / L2 / 8 + (5 * r3 * r3) / L2 / 24) * sk) * sk;
666
+ // log(L2/a) (L2 here in units of 2^(2k)), without cancellation near w = 0
667
+ let lr;
668
+ if (k === 0 && w < 700) {
669
+ const x = Math.expm1(w) - f[1] / a;
670
+ lr = Math.abs(x) < 0.5 ? Math.log1p(x) : Math.log(Math.exp(w) - f[1] / a);
671
+ }
672
+ else
673
+ lr = Math.log(L2) + 2 * k * Math.LN2 - la;
674
+ // a (e^w - 1 - w), with a e^w from its log beyond the overflow of e^w (it may still overflow: the log is then -Inf)
675
+ const aE = w > 700 ? Math.exp(la + w) - a * (1 + w) : a * expm1mxNum(w);
676
+ const rest = -0.5 * lr - stirlerr(a) + Math.log1p(c1) - aE;
677
+ const ud = Math.abs(w) < 1
678
+ ? ddAdd(twoSum(t, -delta), twoProd(t, Math.expm1(w / 2)))
679
+ : ddAdd(ddMulNum(ddExp([w / 2, 0]), t), [-delta, 0]);
680
+ let value;
681
+ if (cdf) {
682
+ const l = logPhiDD(ud);
683
+ const log = l[0] + (l[1] + rest);
684
+ value = { lin: log < -745 ? 0 : pnorm(ud[0]) * (1 + ud[1] * millsInv(ud[0])) * Math.exp(rest), log };
685
+ }
686
+ else {
687
+ // (u²/2 as u (u/2): u² alone overflows from |u| = 1.34e154, u²/2 from 1.9e154)
688
+ const uh = ddMul(ud, [ud[0] / 2, ud[1] / 2]);
689
+ const log = -uh[0] + (rest + w / 2 - LN_SQRT_2PI - uh[1]);
690
+ value = { lin: log < -745 ? 0 : Math.exp(log), log };
691
+ }
692
+ const q = cdf ? Math.abs(vs) / 2 / (Math.sqrt(L2) * Math.max(1, -u)) : 0;
693
+ const inv = (sk * sk) / L2;
694
+ return inv * inv + q ** 6 <= 1e-17 * Math.max(1, Math.abs(value.log)) ? value : undefined;
695
+ }
696
+ /**
697
+ * Beyond this far log estimate (farLogEstimate), the double-precision log of the integrand has an absolute error (eps
698
+ * times it) that no longer locates the peak of the trapezoidal sum (the sum overflowed or vanished from an estimate of
699
+ * about 5e11 on: pt(5, 3, ncp 1e7) gave a log of +Infinity, pt(1, 10, ncp 1e9) NaN). There the integral is taken by
700
+ * zTail, laplaceWide or, where the peak is broad, with Φ(-δ) (φ(δ) for the density) taken out (integrateShifted)
701
+ */
702
+ const LOG_LARGE = 2 ** 30;
703
+ /**
704
+ * Beyond this |δ| the logs of the integrand reach δ²/2 at some nodes even where the answer is moderate (the old
705
+ * integral gave pt(1.6e15, 0.5, ncp 1e20) a log of +Infinity and pt(7.9e17, 1e5, ncp 1e20) -δ²/2). There the far log
706
+ * estimate is below LOG_LARGE only for t/sqrt(2a) above 2^16, where zTail applies
707
+ */
708
+ const D_LARGE = 2 ** 32;
709
+ /**
710
+ * From this t/sqrt(2a) on (t δ > 0, beyond LOG_LARGE) the integrals are taken over z = Z (zTail). In w the peak narrows
711
+ * as t grows: placing it on the nearest double leaves an error of about L'' ulp(w)²/2, w² eps t²/(8a) relative to the
712
+ * log (180 eps at t/sqrt(2a) = 2^26, w = 27, where pt(t, 3, ncp 1e14) stepped by 0.1 in 1e12); here it is below
713
+ * eps/500 for any w. The terms zTail leaves out are about 64 a⁴/t⁶ in the log, far below eps |log| from here on
714
+ */
715
+ const T_Z = 2 ** 12;
716
+ /**
717
+ * The tails and the density for t/sqrt(2a) >= T_Z, t δ > 0 (here both positive), over z = Z (formula B):
718
+ * P[T <= t] = Φ(-δ) + ∫ φ(z) Q(a, x(z)) dz, P[T > t] = ∫ φ(z) P(a, x(z)) dz,
719
+ * f(t) = 2/(t Γ(a)) ∫ φ(z) x(z)^a e^(-x(z)) dz,
720
+ * x(z) = a ((δ + z)/t)² = x0 (1 + 2z/δ + z²/δ²), x0 = a (δ/t)² (the integrals over z > -δ). With g = log Q, log P or
721
+ * a log x - x, and its derivatives in log x, g1 = x g', g2 = x² g'' (these do not overflow for a tiny a, where g' is
722
+ * about 1/(x log(1/x))), the integral is e^g(x0) E[e^(b Z + k Z²/2)] = e^g(x0) exp(b²/(2(1 - k))) / sqrt(1 - k),
723
+ * b = 2 g1/δ, k = (4 g2 + 2 g1)/δ² (g to second order in z). The terms left out are about 64 a⁴/t⁶ in the log, and
724
+ * z below -δ (cut off) lies some δ beyond the peak at z = b (|b| is at most about 2a δ/t², below δ 2^-23)
725
+ */
726
+ function zTail(a, t, delta, kind) {
727
+ const y = delta / t;
728
+ const x0 = a * y * y;
729
+ if (!Number.isFinite(x0)) {
730
+ // (x0 beyond the double range: Q and the density are 0 to the double, P is 1)
731
+ const log = kind === "upper" ? 0 : kind === "lower" ? pnorm(-delta, { logP: true }) : -Infinity;
732
+ return { lin: Math.exp(log), log };
733
+ }
734
+ let base;
735
+ let g1;
736
+ let g2;
737
+ if (kind === "pdf") {
738
+ base = Math.LN2 - lgamma1p(a) + Math.log(a) - Math.log(t) + a * Math.log(x0) - x0;
739
+ g1 = a - x0;
740
+ g2 = -a;
741
+ }
742
+ else {
743
+ const upper = kind === "upper";
744
+ base = gammaInc(a, x0, upper, true);
745
+ if (!upper && x0 > 1e4 * (a + 1)) {
746
+ // Q = h S, h = x^(a-1) e^-x / Γ(a), S = Σ (a-1)...(a-k)/x^k: x d log Q/dx = -x/S, and x² d²log Q/dx² = x² S'/S²
747
+ // (from the logs of h and Q, which are both about -x, the derivative would keep an error of eps x)
748
+ let term = 1;
749
+ let sum = 1;
750
+ let dsum = 0;
751
+ for (let j = 1; j < 20; j++) {
752
+ term *= (a - j) / x0;
753
+ sum += term;
754
+ dsum -= j * term;
755
+ if (Math.abs(term) < 1e-20)
756
+ break;
757
+ }
758
+ g1 = -x0 / sum;
759
+ g2 = (dsum * x0) / (sum * sum);
760
+ }
761
+ else {
762
+ // x d log G/dx = ∓x^a e^-x / (Γ(a) G) for G = Q, P, and x² d²log G/dx² = g1 (a - 1 - x - g1)
763
+ const h = Math.exp(dpoisRaw(a, x0, true) + Math.log(a) - base);
764
+ g1 = upper ? h : -h;
765
+ g2 = g1 * (a - 1 - x0 - g1);
766
+ }
767
+ }
768
+ const b = (2 * g1) / delta;
769
+ const k = (4 * g2 + 2 * g1) / delta / delta;
770
+ const logI = base + (b * b) / (2 * (1 - k)) - 0.5 * Math.log1p(-k);
771
+ const log = kind === "lower" ? logAddExp(pnorm(-delta, { logP: true }), logI) : logI;
772
+ return { lin: log < -745 ? 0 : Math.exp(log), log };
773
+ }
774
+ /** log |e^x - 1| (x beyond 40: x, to 1e-17) */
775
+ function logAbsExpm1(x) {
776
+ return x > 40 ? x : Math.log(Math.abs(Math.expm1(x)));
777
+ }
778
+ /** log Φ(y - δ) - log Φ(-δ), where both are far in the left tail as the difference of the exponents and erfcx */
779
+ function logPhiRatio(y, delta) {
780
+ const z1 = y - delta;
781
+ if (z1 < -5 && delta > 5) {
782
+ return y * (delta - y / 2) + Math.log(erfcxNonNegative(-z1 * Math.SQRT1_2) / erfcxNonNegative(delta * Math.SQRT1_2));
783
+ }
784
+ return pnorm(z1, { logP: true }) - pnorm(-delta, { logP: true });
785
+ }
786
+ /**
787
+ * The integral beyond LOG_LARGE where Laplace's method does not apply (a broad peak: t S small beside δ), as Φ(-δ) times
788
+ * E[Φ(t S - δ)/Φ(-δ)] (the density: φ(δ) times E[S φ(t S - δ)/φ(δ)]): the log of the ratio, log Φ(t S - δ) - log Φ(-δ)
789
+ * or t S (δ - t S/2), is of a moderate size there, and the trapezoidal sum of formula A finds its peak
790
+ */
791
+ function integrateShifted(pr) {
792
+ const shift = pr.kind === "cdf" ? pnorm(-pr.delta, { logP: true }) : -(pr.delta * (pr.delta / 2)) - LN_SQRT_2PI;
793
+ if (shift === -Infinity)
794
+ return { lin: 0, log: -Infinity };
795
+ const { a, t, delta } = pr;
796
+ // log λ, λ = |t δ|: for t δ < 0 the ratio is about e^(-λ S) (with S for the density), and the peak, at S = (2a + m)/λ
797
+ // (m = 0, 1 for the distribution function and the density), falls out of the range of w (S below e^-700) from
798
+ // λ = e^690 on. There the integral is the Laplace transform of the density of S near 0, 2 a^a/Γ(a) S^(2a-1):
799
+ // E[S^m e^(-λ S)] = 2 a^a Γ(2a + m) / (Γ(a) λ^(2a + m)), to relative order (2a + m)/λ (also beside 1/sqrt(a), the scale
800
+ // on which the density of S departs from its power, and the departure of the ratio from e^(-λ S), of order m/δ²)
801
+ const lLam = Math.log(Math.abs(t)) + Math.log(Math.abs(delta));
802
+ if (t * delta < 0 && lLam > 690) {
803
+ const p = pr.kind === "cdf" ? 2 * a : 2 * a + 1;
804
+ const log = shift + Math.LN2 + a * Math.log(a) - (lgamma1p(a) - Math.log(a)) + (lgamma1p(p) - Math.log(p)) - p * lLam;
805
+ return { lin: log < -745 ? 0 : Math.exp(log), log };
806
+ }
807
+ if (!(pr.kind === "cdf" && a < A_TINY)) {
808
+ const sp = { ...pr, shift };
809
+ return integrateCore(sp, true, bracketedPeak(sp));
810
+ }
811
+ // For a tiny a most of the probability of S lies near 0, spread over w down to about -1/a, where ρ is 1: the integral
812
+ // is 1 ∓ E[|ρ - 1|] (t < 0, t > 0), whose integrand peaks where t S δ is of order 1
813
+ const sp = { ...pr, shift, complement: true };
814
+ const lc = integrateCore(sp, true, bracketedPeak(sp)).log;
815
+ const log = shift + (t < 0 ? Math.log1p(-Math.exp(lc)) : logAddExp(0, lc));
816
+ return { lin: log < -745 ? 0 : Math.exp(log), log };
817
+ }
818
+ /**
819
+ * The peak of the log integrand by bisection on the sign of L' (the peak of integrateShifted is broad, so 1e-12 in w is
820
+ * ample). findPeak's Newton steps stall where L falls steeply over the range: for a large negative t S, L' is about
821
+ * t S δ / 2 at w = 0, and its steps of 1e-14 were taken for convergence
822
+ */
823
+ function bracketedPeak(pr) {
824
+ let lo = -1400;
825
+ let hi = 1418;
826
+ for (let i = 0; i < 200 && hi - lo > 1e-12 * Math.max(1, Math.abs(lo)); i++) {
827
+ const m = (lo + hi) / 2;
828
+ const d1 = logIntegrand(pr, m)[1];
829
+ // (a d1 that is not formed lies beyond the double range on that side)
830
+ if (d1 > 0 || (Number.isNaN(d1) && m < 0))
831
+ lo = m;
832
+ else
833
+ hi = m;
834
+ }
835
+ const w = (lo + hi) / 2;
836
+ let [L, , d2] = logIntegrand(pr, w);
837
+ if (Number.isNaN(d2)) {
838
+ // (L'' from the differences of L')
839
+ const h = 1e-4;
840
+ d2 = (logIntegrand(pr, w + h)[1] - logIntegrand(pr, w - h)[1]) / (2 * h);
841
+ }
842
+ return { w, sigma: d2 < 0 ? Math.min(1 / Math.sqrt(-d2), 10) : 1, L };
843
+ }
475
844
  function logAddExp(x, y) {
476
845
  if (x === -Infinity)
477
846
  return y;
@@ -480,24 +849,26 @@ function logAddExp(x, y) {
480
849
  return x > y ? x + Math.log1p(Math.exp(y - x)) : y + Math.log1p(Math.exp(x - y));
481
850
  }
482
851
  /** Linear value and log of the integral (the log may be NaN unless needLog) */
483
- function integrateCore(pr, needLog, peak) {
852
+ function integrateCore(pr, needLog, peak, ddOffset = false) {
484
853
  const { w, sigma, L } = peak ?? findPeak(pr);
485
854
  // With a peak value this small the linear answer underflows to 0 (even after multiplying by the width)
486
855
  if (!needLog && L < -800)
487
856
  return { lin: 0, log: NaN };
488
857
  // If summing linearly would overflow or underflow, subtract the peak value L before summing
489
- const useLog = L < -650 || L > 650;
490
- const offset = useLog ? L : 0;
858
+ const useLog = L < -650 || L > 650 || pr.shift !== undefined || ddOffset;
859
+ // (with ddOffset, the log of the peak in double-double: subtracted from the nodes' in double-double)
860
+ const off = ddOffset ? integrand(pr, [w, 0], true) : [useLog ? L : 0, 0];
861
+ const offset = off[0];
491
862
  // Peak value (approximate) used by the fast-path test
492
863
  const peakVal = useLog ? 0 : Math.exp(L);
493
864
  // Convergence test: halving the step roughly squares the error, so if the difference is below this the finer
494
865
  // value is accurate enough. In deep tails (summed on the log scale) the node values themselves carry an error
495
866
  // of about eps |L|, so stop there
496
- const tol = useLog ? Math.max(1e-15, 2e-16 * Math.abs(L)) : 1e-15;
867
+ const tol = useLog && !ddOffset ? Math.max(1e-15, 2e-16 * Math.abs(L)) : 1e-15;
497
868
  let h = 0.5;
498
- let s = trapezoid(pr, w, sigma, h, useLog, offset, false, peakVal) * h;
869
+ let s = trapezoid(pr, w, sigma, h, useLog, offset, false, peakVal, ddOffset ? off[1] : undefined) * h;
499
870
  for (let level = 0; level < 6; level++) {
500
- const odd = trapezoid(pr, w, sigma, h / 2, useLog, offset, true, peakVal) * (h / 2);
871
+ const odd = trapezoid(pr, w, sigma, h / 2, useLog, offset, true, peakVal, ddOffset ? off[1] : undefined) * (h / 2);
501
872
  const s2 = s / 2 + odd;
502
873
  h /= 2;
503
874
  const conv = Math.abs(s2 - s) <= tol * Math.abs(s2);
@@ -507,6 +878,15 @@ function integrateCore(pr, needLog, peak) {
507
878
  }
508
879
  if (!useLog)
509
880
  return { lin: s, log: Math.log(s) };
881
+ if (pr.shift !== undefined) {
882
+ // (only beyond LOG_LARGE, where the linear value is 0; with complement, E|ρ - 1| itself, without the shift)
883
+ const log = (pr.complement ? 0 : pr.shift) + offset + Math.log(s);
884
+ return { lin: log < -745 ? 0 : Math.exp(log), log };
885
+ }
886
+ if (ddOffset) {
887
+ const log = offset + (off[1] + Math.log(s));
888
+ return { lin: log < -745 ? 0 : Math.exp(log), log };
889
+ }
510
890
  // exp(offset) s: take exp of offset first and multiply (exp(offset + log s) would have an error |offset| times larger)
511
891
  const lin = offset > -700 ? Math.exp(offset) * s : Math.exp(offset + 700) * s * Math.exp(-700);
512
892
  return { lin, log: offset + Math.log(s) };
@@ -539,7 +919,8 @@ function farTails(t, a, delta, lower) {
539
919
  const s = Math.sign(t);
540
920
  const farLower = s < 0;
541
921
  const f0 = pntBoth(s * T0, 2 * a, delta, farLower);
542
- const k = 2 * a * (Math.log(Math.abs(t)) - Math.log(T0));
922
+ const r = Math.log(Math.abs(t)) - Math.log(T0);
923
+ const k = 2 * a * r;
543
924
  const far = { lin: f0.lin > 0 ? f0.lin * Math.exp(-k) : Math.exp(f0.log - k), log: f0.log - k };
544
925
  if (lower === farLower)
545
926
  return far;
@@ -547,7 +928,9 @@ function farTails(t, a, delta, lower) {
547
928
  return { lin: 1 - far.lin, log: Math.log1p(-far.lin) };
548
929
  const n0 = pntBoth(s * T0, 2 * a, delta, !farLower);
549
930
  const gain = -Math.expm1(-k);
550
- return { lin: n0.lin + f0.lin * gain, log: logAddExp(n0.log, f0.log + Math.log(gain)) };
931
+ // (log k from log 2a where k is so small that it may be subnormal: for a subnormal a it kept a few bits only)
932
+ const logGain = k < 1e-10 ? Math.log(2 * a) + Math.log(r) - k / 2 : Math.log(gain);
933
+ return { lin: n0.lin + f0.lin * gain, log: logAddExp(n0.log, f0.log + logGain) };
551
934
  }
552
935
  /**
553
936
  * Whether |t| is so small that P[T <= t] = Φ(-δ) and P[T > t] = Φ(δ), their values at t = 0, to double precision.
@@ -557,7 +940,18 @@ function farTails(t, a, delta, lower) {
557
940
  * e^w overflows
558
941
  */
559
942
  function nearZero(t, a, delta) {
560
- return Math.abs(t) * Math.sqrt((4 * a + 2 * delta * delta + 800) / a) * (Math.abs(delta) + 2) <= 1e-17;
943
+ // (|t|/sqrt(a) first, and sqrt(y1) as a hypot: y1/a overflowed for a below about 1e-300 with a large δ, and at t = 0
944
+ // the test was NaN, false, so that the integral was taken at t = 0 and gave NaN to qt)
945
+ const r = (Math.abs(t) / Math.sqrt(a)) * Math.hypot(Math.SQRT2 * delta, Math.sqrt(4 * a + 800)) * (Math.abs(delta) + 2);
946
+ if (Number.isFinite(r))
947
+ return r <= 1e-17;
948
+ // (a factor overflowed, or |t|/sqrt(a) underflowed against it, at δ near the overflow threshold: by logs)
949
+ const l = Math.log(Math.abs(t)) -
950
+ 0.5 * Math.log(a) +
951
+ 0.5 * Math.LN2 +
952
+ Math.log(Math.hypot(delta, Math.sqrt(2 * a + 400))) +
953
+ Math.log(Math.abs(delta) + 2);
954
+ return l <= Math.log(1e-17);
561
955
  }
562
956
  /** Linear value and log of P[T <= t] (lower) / P[T > t] (the log may be NaN unless needLog) */
563
957
  function pntBoth(t, df, delta, lower, needLog = true) {
@@ -598,11 +992,71 @@ function dntRaw(x, df, delta, log) {
598
992
  const v = integrate(problem(a, x, delta, "pdf"), log);
599
993
  return log ? v.log : v.lin;
600
994
  }
601
- export function dnt1(x, df, ncp, log) {
602
- if (Number.isNaN(x) || Number.isNaN(df) || Number.isNaN(ncp))
995
+ /**
996
+ * Above this df the central and noncentral t are taken from their limits (hugeDf*; shared with t.ts). The t
997
+ * differs from the normal by terms of relative order t²/ν and 1/ν: where y = t²/ν < 1e-17 it is the normal to the
998
+ * double (the absolute error in the log, about t⁴/ν, is below 1e-180 wherever the linear value is above the
999
+ * underflow), and beyond, |t| > 3e91, the log of the far tail and of the density is -(ν/2) log1p(y) up to terms
1000
+ * below 1e-179 of it. The general code fails from about 1.3e300 on (NaN where its intermediate terms overflow)
1001
+ */
1002
+ export const HUGE_DF = 1e200;
1003
+ /** y = t²/ν (t² may overflow on its own) */
1004
+ export function hugeDfRatio(t, n) {
1005
+ const u = t / Math.sqrt(n);
1006
+ return u * u;
1007
+ }
1008
+ /**
1009
+ * Log of the far tail beyond |t| and of the density at t (relative error about eps) for n > HUGE_DF and
1010
+ * hugeDfRatio(t, n) >= 1e-17: -(n/2) log1p(t²/n), formed without overflow
1011
+ */
1012
+ export function hugeDfTailLog(t, n) {
1013
+ const u = Math.abs(t) / Math.sqrt(n);
1014
+ // log1p(u²) = 2 log u + log1p(1/u²) where u² is huge (n log u may overflow: the log is then -Infinity, as it is)
1015
+ if (u > 1e8)
1016
+ return -n * (Math.log(u) + 0.5 * Math.log1p(1 / (u * u)));
1017
+ const y = u * u;
1018
+ // (n/2) log1p(y) = (t²/2) log1p(y)/y, the ratio by its series for a small y (error y⁴/5)
1019
+ const g = y < 1e-5 ? 1 - y * (1 / 2 - y * (1 / 3 - y / 4)) : Math.log1p(y) / y;
1020
+ return -0.5 * Math.abs(t) * (Math.abs(t) * g);
1021
+ }
1022
+ /**
1023
+ * |t| with hugeDfTailLog(t, n) = logTarget (logTarget < 0), Infinity beyond the largest double: t² = n expm1(-2 logTarget / n).
1024
+ * (sqrt(n) is taken apart: through exp(log t) its log, up to 354, would multiply the rounding error)
1025
+ */
1026
+ export function hugeDfTailQuantile(logTarget, n) {
1027
+ const r = 2 * (-logTarget / n);
1028
+ return r < 700 ? Math.sqrt(n) * Math.sqrt(Math.expm1(r)) : Math.sqrt(n) * Math.exp(r / 2);
1029
+ }
1030
+ /**
1031
+ * P[T <= t] (lower) / P[T > t] for n > HUGE_DF and hugeDfRatio(t, n) >= 1e-17 from hugeDfTailLog: the tail beyond |t|
1032
+ * is its exp (0), the other is 1
1033
+ */
1034
+ export function hugeDfTail(t, n, lowerTail, logP) {
1035
+ const l = hugeDfTailLog(t, n);
1036
+ if (t < 0 === lowerTail)
1037
+ return logP ? l : Math.exp(l);
1038
+ return logP ? Math.log1p(-Math.exp(l)) : 1 - Math.exp(l);
1039
+ }
1040
+ /**
1041
+ * Whether the noncentral t at n > HUGE_DF and hugeDfRatio(t, n) >= 1e-17 has the central far tail and density
1042
+ * (hugeDfTailLog): δ shifts their log by about δ min(|t|, sqrt(n)), below 1e-19 of it here
1043
+ */
1044
+ function hugeDfCentral(t, n, delta) {
1045
+ return Math.abs(delta) <= 1e-20 * Math.min(Math.abs(t), Math.sqrt(n));
1046
+ }
1047
+ /**
1048
+ * df with a nonzero half: the smallest subnormal, whose half rounds to 0, is taken as twice itself (a = 5e-324). Below
1049
+ * about 1e-308 a = df/2 is rounded to the subnormal grid anyway; only the terms of order a beside Φ(∓δ) feel that
1050
+ */
1051
+ function halvable(df) {
1052
+ return df === Number.MIN_VALUE ? 2 * df : df;
1053
+ }
1054
+ export function dnt1(x, df0, ncp, log) {
1055
+ if (Number.isNaN(x) || Number.isNaN(df0) || Number.isNaN(ncp))
603
1056
  return NaN;
604
- if (df <= 0)
1057
+ if (df0 <= 0)
605
1058
  return NaN;
1059
+ const df = halvable(df0);
606
1060
  if (!Number.isFinite(x) || !Number.isFinite(ncp))
607
1061
  return log ? -Infinity : 0;
608
1062
  if (df === Infinity) {
@@ -610,13 +1064,22 @@ export function dnt1(x, df, ncp, log) {
610
1064
  const lv = -0.5 * z * z - LN_SQRT_2PI;
611
1065
  return log ? lv : Math.exp(lv);
612
1066
  }
1067
+ if (df > HUGE_DF) {
1068
+ if (hugeDfRatio(x, df) < 1e-17)
1069
+ return dnorm(x - ncp, { log });
1070
+ if (hugeDfCentral(x, df, ncp)) {
1071
+ const lv = hugeDfTailLog(x, df);
1072
+ return log ? lv : Math.exp(lv);
1073
+ }
1074
+ }
613
1075
  return dntRaw(x, df, ncp, log);
614
1076
  }
615
- export function pnt1(q, df, ncp, lowerTail, logP) {
616
- if (Number.isNaN(q) || Number.isNaN(df) || Number.isNaN(ncp))
1077
+ export function pnt1(q, df0, ncp, lowerTail, logP) {
1078
+ if (Number.isNaN(q) || Number.isNaN(df0) || Number.isNaN(ncp))
617
1079
  return NaN;
618
- if (df <= 0)
1080
+ if (df0 <= 0)
619
1081
  return NaN;
1082
+ const df = halvable(df0);
620
1083
  const zero = lowerTail ? (logP ? -Infinity : 0) : logP ? 0 : 1;
621
1084
  const one = lowerTail ? (logP ? 0 : 1) : logP ? -Infinity : 0;
622
1085
  if (q === Infinity)
@@ -632,22 +1095,41 @@ export function pnt1(q, df, ncp, lowerTail, logP) {
632
1095
  return pnorm(q - ncp, { lowerTail, logP });
633
1096
  if (q === 0)
634
1097
  return pnorm(-ncp, { lowerTail, logP });
1098
+ if (df > HUGE_DF) {
1099
+ if (hugeDfRatio(q, df) < 1e-17)
1100
+ return pnorm(q - ncp, { lowerTail, logP });
1101
+ // The far tail beyond |q| (R 4.5.2 gives 0.5 for pt(-4.05e269, 3.586e307, ncp = 1), far in the left tail of
1102
+ // what is N(1, 1) to the double; the lower tail is 0 here)
1103
+ if (hugeDfCentral(q, df, ncp))
1104
+ return hugeDfTail(q, df, lowerTail, logP);
1105
+ }
635
1106
  return pntRaw(q, df, ncp, lowerTail, logP);
636
1107
  }
637
- export function qnt1(p, df, ncp, lowerTail, logP) {
638
- if (Number.isNaN(p) || Number.isNaN(df) || Number.isNaN(ncp))
1108
+ export function qnt1(p, df0, ncp, lowerTail, logP) {
1109
+ if (Number.isNaN(p) || Number.isNaN(df0) || Number.isNaN(ncp))
639
1110
  return NaN;
640
- if (df <= 0)
1111
+ if (df0 <= 0)
641
1112
  return NaN;
1113
+ const df = halvable(df0);
642
1114
  const b = quantileBoundaries(p, -Infinity, Infinity, lowerTail, logP);
643
1115
  if (b !== undefined)
644
1116
  return b;
645
1117
  if (df === Infinity)
646
1118
  return ncp + qnorm(p, { lowerTail, logP });
647
- // ncp = ±Inf concentrates the distribution at ±∞ and the quantile is undefined, so NaN (R's answer mixes NaN and ±Inf depending on p)
1119
+ // ncp = ±Inf puts all the probability at ±∞ (pt is 0 or 1 at every finite t, in R too), so every quantile inside
1120
+ // (0, 1) is ±∞, as already for df = Inf above (R gives NaN for a finite df)
648
1121
  if (!Number.isFinite(ncp))
649
- return NaN;
1122
+ return ncp;
650
1123
  const { lower, logTarget, linearTarget } = smallerTail(p, lowerTail, logP);
1124
+ if (df > HUGE_DF) {
1125
+ // The quantiles of the limits of pnt1
1126
+ const x = ncp + qnorm(p, { lowerTail, logP });
1127
+ if (hugeDfRatio(x, df) < 1e-17)
1128
+ return x;
1129
+ const y = hugeDfTailQuantile(logTarget, df);
1130
+ if (hugeDfCentral(y, df, ncp))
1131
+ return lower ? -y : y;
1132
+ }
651
1133
  // Starting value: normal approximation (mean δ; t spreads a little in the direction of δ)
652
1134
  const z = qnorm(logTarget, { lowerTail: lower, logP: true });
653
1135
  const x0 = ncp + z * Math.sqrt(1 + (ncp * ncp) / (2 * df));
@@ -671,6 +1153,14 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
671
1153
  }
672
1154
  return log ? last.log : last.lin;
673
1155
  };
1156
+ // Where the normal start is beyond 1e300 or not finite (ncp near the largest double, or a huge ncp^2 / df), the
1157
+ // quantile can lie beyond the largest double for any df: if the target is not reached there, it is ±Infinity. (The
1158
+ // solver broke down outside the doubles and returned 1 for qt(0.9, 2, ncp = 1e308); issue #136)
1159
+ if (!(Math.abs(x0) <= 1e300)) {
1160
+ const lMax = cdfY(Number.MAX_VALUE, lowerY, true);
1161
+ if (lowerY ? lMax < logTarget : lMax > logTarget)
1162
+ return s * Infinity;
1163
+ }
674
1164
  // In the far tail, if the target is smaller than the probability at |t| = T0, solve directly with the power law
675
1165
  const T0 = farLimit(df / 2, ncp);
676
1166
  let hi = Infinity;
@@ -678,7 +1168,7 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
678
1168
  const lT0 = farTailLog(s * T0, df / 2, ncp);
679
1169
  if (logTarget < lT0) {
680
1170
  const ly = Math.log(T0) + (lT0 - logTarget) / df;
681
- return ly > 709.78 ? s * Infinity : s * Math.exp(ly);
1171
+ return s * Math.exp(ly); // (Infinity where the quantile is beyond the largest double)
682
1172
  }
683
1173
  hi = T0;
684
1174
  }
@@ -687,6 +1177,17 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
687
1177
  // the largest double (that needs 2a log(1.8e308) < log(2c), a < 5e-4): the quantile is beyond it
688
1178
  return s * Infinity;
689
1179
  }
1180
+ // Where the normal start falls on the other side of 0 (a small ν with a large δ, for one): on the side of δ,
1181
+ // P[sT <= y] = P[s Z + |δ| <= y S] is about P[S >= |δ|/y] = Q(a, a δ²/y²) when Φ is a step on the scale of S, so y
1182
+ // from the gamma quantile. (The start was 1, far above the quantile, from where the first step went to y = 0 and
1183
+ // the solver bisected back in log y across the doubly exponential fall of P: 50 ms at df = 1e-200, ncp = 1e4)
1184
+ const sideStart = () => {
1185
+ if (s * ncp <= 0)
1186
+ return 1;
1187
+ const g = qgammaStd(logTarget, df / 2, !lowerY, true);
1188
+ const y0 = Math.abs(ncp) * Math.sqrt(df / 2 / g);
1189
+ return y0 > 0 && Number.isFinite(y0) ? y0 : 1;
1190
+ };
690
1191
  const y = invertContinuous({
691
1192
  logTarget,
692
1193
  ...(linearTarget !== undefined && { linearTarget }),
@@ -694,7 +1195,7 @@ export function qnt1(p, df, ncp, lowerTail, logP) {
694
1195
  cdf: (y, l) => cdfY(y, l, false),
695
1196
  cdfLog: (y, l) => cdfY(y, l, true),
696
1197
  pdfLog: (y) => dntRaw(s * y, df, ncp, true),
697
- x0: Math.min(Math.abs(x0) > 0 && Number.isFinite(x0) && Math.sign(x0) === s ? Math.abs(x0) : 1, hi / 2),
1198
+ x0: Math.min(Math.abs(x0) > 0 && Number.isFinite(x0) && Math.sign(x0) === s ? Math.abs(x0) : sideStart(), hi / 2),
698
1199
  lo: 0,
699
1200
  hi,
700
1201
  positive: true,