@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
@@ -8,10 +8,11 @@
8
8
  // beta(1, 1), beta with both shapes below 1, arcsine), the larger of two adjacent maxima of a discrete
9
9
  // distribution, and the end point where the density diverges (gamma with shape < 1).
10
10
  import { dqagie, dqagse } from "../integrate/quadpack.js";
11
- import { ddAdd, ddMul, ddSub } from "../special/dd.js";
12
- import { gamma as gammaFn } from "../special/gamma.js";
11
+ import { ddAdd, ddLog, ddMul, ddMulNum, ddSub, twoProd } from "../special/dd.js";
12
+ import { ddExp } from "../internal/ddexp.js";
13
+ import { gamma as gammaFn, lgamma } from "../special/gamma.js";
13
14
  import { lbeta } from "../special/beta.js";
14
- import { qgamma } from "./gamma.js";
15
+ import { gammaScale, qgamma } from "./gamma.js";
15
16
  import { qchisq } from "./chisq.js";
16
17
  import { qbeta } from "./beta.js";
17
18
  import { qf } from "./f.js";
@@ -20,14 +21,36 @@ import { qbinom } from "./binomial.js";
20
21
  import { qpois } from "./poisson.js";
21
22
  import { qgeom } from "./geometric.js";
22
23
  import { qnbinom } from "./negbinomial.js";
23
- import { qhyper } from "./hypergeometric.js";
24
+ import { dhyper1, qhyper } from "./hypergeometric.js";
24
25
  import { qinvgamma } from "./invgamma.js";
25
26
  import { dkumar1, pkumar1, qkumar, qkumar1 } from "./kumaraswamy.js";
26
27
  import { qtriang } from "./triangular.js";
27
- import { qarcsine } from "./arcsine.js";
28
+ import { ldexp } from "../internal/summary.js";
29
+ import { midpoint } from "../internal/extremes.js";
30
+ import { splitDouble } from "../linalg/dot.js";
28
31
  const NAN = { mean: NaN, variance: NaN, sd: NaN, median: NaN, mode: NaN, skewness: NaN, kurtosis: NaN };
29
- function make(mean, variance, median, mode, skewness, kurtosis) {
30
- return { mean, variance, sd: Math.sqrt(variance), median, mode, skewness, kurtosis };
32
+ /** A point mass at 0: no skewness or kurtosis */
33
+ const POINT_AT_0 = { mean: 0, variance: 0, sd: 0, median: 0, mode: 0, skewness: NaN, kurtosis: NaN };
34
+ /**
35
+ * sdDirect: the standard deviation formed without the variance, used where the variance overflowed or lost digits
36
+ * below the smallest normal number (normal(sd = 1e200) has variance Inf and sd 1e200, normal(sd = 1e-200) variance 0)
37
+ */
38
+ function make(mean, variance, median, mode, skewness, kurtosis, sdDirect) {
39
+ const sd = sdDirect === undefined || (variance >= MIN_NORMAL && variance < Infinity) ? Math.sqrt(variance) : sdDirect;
40
+ return { mean, variance, sd, median, mode, skewness, kurtosis };
41
+ }
42
+ const MIN_NORMAL = 2 ** -1022;
43
+ /**
44
+ * v = f(x_1, ..., x_n), a product of powers x_i^d_i (given as [x_i, d_i]) and factors of moderate size. Where v left
45
+ * the normal range and the x_i are finite and non-zero, f again at x_i 2^-e_i (each in [1, 2)), multiplied back by
46
+ * 2^(sum d_i e_i): the same roundings as f where the result is normal, but no intermediate power overflows or
47
+ * underflows (the variance (max - min)^2 / 12 of unif(0, 2e154) was Infinity for 3.3e307; issue #376)
48
+ */
49
+ function rescaled(v, f, ...powers) {
50
+ if ((v >= MIN_NORMAL && v < Infinity) || !powers.every(([x]) => Number.isFinite(x) && x !== 0))
51
+ return v;
52
+ const e = powers.map(([x]) => Math.floor(Math.log2(Math.abs(x))));
53
+ return ldexp(f(...powers.map(([x], i) => ldexp(x, -e[i]))), powers.reduce((k, [, d], i) => k + d * e[i], 0));
31
54
  }
32
55
  /**
33
56
  * Variance, skewness and excess kurtosis from the central moments E[(X - mean)^n], integrated numerically from the
@@ -38,17 +61,110 @@ function make(mean, variance, median, mode, skewness, kurtosis) {
38
61
  function shape(f, mean, lower, upper) {
39
62
  return central((t) => t, f, mean, mean, lower, upper);
40
63
  }
64
+ /** Whether a QUADPACK result can be used: it converged, or its error estimate is still within 1e-8 of it */
65
+ function converged(r) {
66
+ return r.ier === 0 || r.abserr <= 1e-8 * Math.abs(r.result);
67
+ }
68
+ /**
69
+ * Variance, skewness and excess kurtosis from the logs l_r of the raw moments E[X^r], r = 1..4, through the ratios
70
+ * rho_r = E[X^r] / E[X]^r taken in logs (so heavy tails, where the integrals of shape() do not converge, neither
71
+ * overflow nor cancel: the leading terms dominate there)
72
+ */
73
+ function fromLogRawMoments([l1, l2, l3, l4]) {
74
+ const r2 = l2 - 2 * l1;
75
+ const r3 = l3 - 3 * l1;
76
+ const r4 = l4 - 4 * l1;
77
+ const lv = r2 + Math.log(-Math.expm1(-r2)); // log(rho_2 - 1)
78
+ return {
79
+ variance: Math.exp(2 * l1 + lv),
80
+ skewness: Math.exp(r3 - 1.5 * lv) * (1 - 3 * Math.exp(r2 - r3) + 2 * Math.exp(-r3)),
81
+ kurtosis: Math.exp(r4 - 2 * lv) * (1 - 4 * Math.exp(r3 - r4) + 6 * Math.exp(r2 - r4) - 3 * Math.exp(-r4)) - 3,
82
+ ok: true,
83
+ };
84
+ }
41
85
  /** shape() over t: x(t) with weight w(t), the integral split at t = split where x = mean */
42
86
  function central(x, w, mean, split, lower, upper) {
43
87
  const tol = 50 * Number.EPSILON;
88
+ let ok = true;
44
89
  const c = [2, 3, 4].map((n) => {
45
90
  const g = (t) => (x(t) - mean) ** n * w(t);
46
- const left = dqagse(g, lower, split, 0, tol, 200).result;
47
- const right = upper === Infinity ? dqagie(g, split, 1, 0, tol, 200).result : dqagse(g, split, upper, 0, tol, 200).result;
48
- return left + right;
91
+ const left = dqagse(g, lower, split, 0, tol, 200);
92
+ const right = upper === Infinity ? dqagie(g, split, 1, 0, tol, 200) : dqagse(g, split, upper, 0, tol, 200);
93
+ if (!converged(left) || !converged(right))
94
+ ok = false;
95
+ return left.result + right.result;
49
96
  });
50
97
  const v = c[0];
51
- return { variance: v, skewness: c[1] / v ** 1.5, kurtosis: c[2] / (v * v) - 3 };
98
+ // (as in expShape: v^1.5 and v^2 underflow where v is small, kumar(1e-220, 1) had skewness and kurtosis Infinity;
99
+ // issue #386)
100
+ const d3 = v ** 1.5;
101
+ const d4 = v * v;
102
+ return {
103
+ variance: v,
104
+ skewness: d3 >= MIN_NORMAL ? c[1] / d3 : c[1] / v / Math.sqrt(v),
105
+ kurtosis: (d4 >= MIN_NORMAL ? c[2] / d4 : c[2] / v / v) - 3,
106
+ ok,
107
+ };
108
+ }
109
+ /** Shapes above this (Weibull's k, Kumaraswamy's a) go through expShape(); at 100 central() is still within 2e-14 */
110
+ const LARGE_SHAPE = 100;
111
+ /**
112
+ * Moments of X = c exp(Z / s) for a large shape s, through T = s expm1(log(e) / s) = s (X / c - 1), e the base
113
+ * variable (Weibull: e ~ Exp(1), c = 1; Kumaraswamy: e = b W with W ~ Beta(1, b), c = b^(-1/a)), integrated over the
114
+ * pieces. X lies within O(1/s) of c, too narrow for the quadrature in x (and the raw moments Gamma(1 + r/k) round to
115
+ * 1): k = 1e4 gave the skewness -3.03 for -1.139, k = 1e308 sd 0 and NaN (issues #240, #249). T has a spread of
116
+ * order 1 for every shape. Returns E[T], the variance of T and the skewness and kurtosis (those of X), or undefined
117
+ * where an integral did not converge
118
+ */
119
+ function expShape(s, pieces) {
120
+ const tol = 50 * Number.EPSILON;
121
+ // the integral of h w over all pieces, each split at tSplit(piece); undefined unless every part converged or the
122
+ // error estimates together are within 1e-8 of the sum (a part far smaller than the sum may stop at its round-off)
123
+ const over = (h, tSplit) => {
124
+ let sum = 0;
125
+ let err = 0;
126
+ let all = true;
127
+ pieces.forEach((p, i) => {
128
+ const hp = h(i);
129
+ const h0 = p.mass === undefined ? 0 : hp(0);
130
+ const f = (t) => {
131
+ const v = p.w(t);
132
+ return v === 0 ? 0 : (p.mass === undefined ? hp(t) : hp(t) - h0) * v;
133
+ };
134
+ const t0 = tSplit(p);
135
+ for (const [lower, upper] of [[0, t0], [t0, p.upper]]) {
136
+ if (!(upper > lower))
137
+ continue;
138
+ const r = upper === Infinity ? dqagie(f, lower, 1, 0, tol, 200) : dqagse(f, lower, upper, 0, tol, 200);
139
+ sum += r.result;
140
+ err += r.abserr;
141
+ if (r.ier !== 0)
142
+ all = false;
143
+ }
144
+ if (p.mass !== undefined)
145
+ sum += p.mass * h0;
146
+ });
147
+ return all || err <= 1e-8 * Math.abs(sum) ? sum : undefined;
148
+ };
149
+ const Ts = pieces.map((p) => (t) => s * Math.expm1(p.logE(t) / s));
150
+ const meanT = over((i) => Ts[i], (p) => Math.min(1, p.upper / 2));
151
+ if (meanT === undefined || !(meanT / s > -1))
152
+ return undefined;
153
+ // log e where T = E[T]: each piece's integrals are split there
154
+ const split = s * Math.log1p(meanT / s);
155
+ const [c2, c3, c4] = [2, 3, 4].map((n) => over((i) => (t) => (Ts[i](t) - meanT) ** n, (p) => Math.min(Math.max(p.tAt(split), 0), p.upper)));
156
+ if (c2 === undefined || c3 === undefined || c4 === undefined)
157
+ return undefined;
158
+ // (c2^1.5 and c2^2 underflow for b = 1e-300, where the skewness is -1.7e150)
159
+ const d3 = c2 ** 1.5;
160
+ const d4 = c2 * c2;
161
+ return {
162
+ variance: c2,
163
+ skewness: d3 >= MIN_NORMAL ? c3 / d3 : c3 / c2 / Math.sqrt(c2),
164
+ kurtosis: (d4 >= MIN_NORMAL ? c4 / d4 : c4 / c2 / c2) - 3,
165
+ ok: true,
166
+ meanT,
167
+ };
52
168
  }
53
169
  /** floor(a b) of the exact product (a b rounded to double may cross an integer) */
54
170
  function floorProduct(a, b) {
@@ -61,7 +177,20 @@ function productAtMost(a, b, c) {
61
177
  const d = ddSub(ddMul(a, [b, 0]), [c, 0]);
62
178
  return d[0] + d[1] <= 0;
63
179
  }
180
+ /** x r <= (r - 1) mu exactly, for integers x >= 0 and r and a finite mu >= 0 (mu = m 2^e in BigInt) */
181
+ function exactModeTest(x, r, mu) {
182
+ const [m, e] = splitDouble(mu);
183
+ const R = BigInt(r);
184
+ const lhs = BigInt(x) * R;
185
+ const rhs = (R - 1n) * m;
186
+ return e >= 0 ? lhs <= rhs << BigInt(e) : lhs << BigInt(-e) <= rhs;
187
+ }
64
188
  const has = (o, k) => o[k] !== undefined;
189
+ /** ab / (s^2 (s + 1)), from the ratios a / s and b / s when the products overflow or underflow (huge shapes) */
190
+ function betaVariance(a, b, s) {
191
+ const v = (a * b) / (s * s * (s + 1));
192
+ return v > 0 && v < Infinity ? v : ((a / s) * (b / s)) / (s + 1);
193
+ }
65
194
  /**
66
195
  * Mean, variance, standard deviation, median, mode, skewness and excess kurtosis of a distribution, given by the
67
196
  * name of its d/p/q/r functions and their parameters (with the same names and defaults; `gamma` takes `rate` or
@@ -84,7 +213,7 @@ export function distSummary(distribution, params = {}) {
84
213
  const { mean = 0, sd = 1 } = P;
85
214
  if (!(Number.isFinite(mean) && sd > 0 && Number.isFinite(sd)))
86
215
  return NAN;
87
- return make(mean, sd * sd, mean, mean, 0, 0);
216
+ return make(mean, sd * sd, mean, mean, 0, 0, sd);
88
217
  }
89
218
  case "lnorm": {
90
219
  const { meanlog = 0, sdlog = 1 } = P;
@@ -93,35 +222,67 @@ export function distSummary(distribution, params = {}) {
93
222
  const s2 = sdlog * sdlog;
94
223
  const em1 = Math.expm1(s2);
95
224
  const w = Math.exp(s2);
96
- return make(Math.exp(meanlog + s2 / 2), em1 * Math.exp(2 * meanlog + s2), Math.exp(meanlog), Math.exp(meanlog - s2), (w + 2) * Math.sqrt(em1),
225
+ // sqrt(em1): sdlog itself where s2 is below 1e-280 (em1 / s2 is 1 to double precision; s2 underflowed to 0 or onto
226
+ // the subnormals and took the sd and skewness with it: 0 for sdlog = 1e-200; issue #120)
227
+ const rootEm1 = s2 < 1e-280 ? sdlog : Math.sqrt(em1);
228
+ const expHalf = Math.exp(meanlog + s2 / 2);
229
+ const variance = em1 * Math.exp(2 * meanlog + s2);
230
+ const result = make(expHalf, variance, Math.exp(meanlog), Math.exp(meanlog - s2), (w + 2) * rootEm1,
97
231
  // w^4 + 2 w^3 + 3 w^2 - 6 with w = 1 + em1, expanded in em1 (the w form cancels for small sdlog)
98
- em1 * (16 + em1 * (15 + em1 * (6 + em1))));
232
+ em1 * (16 + em1 * (15 + em1 * (6 + em1))), rootEm1 * expHalf);
233
+ if (variance >= MIN_NORMAL && variance < Infinity)
234
+ return result;
235
+ // The variance (and with it maybe the sd) out of the normal range: em1 or the exponential factor overflowed or
236
+ // underflowed although the product may be representable (meanlog 400, sdlog 1e-200 gave 0 * Inf = NaN; meanlog
237
+ // -500, sdlog 27 an infinite variance and sd for e^458 and e^229). Rebuilt from log sd = meanlog + s2 / 2 +
238
+ // log(em1) / 2 in double-double; the sd as before where both of its factors were accurate (issue #120)
239
+ const s2dd = twoProd(sdlog, sdlog);
240
+ const logEm1 = s2 < 1e-280 ? ddMulNum(ddLog([sdlog, 0]), 2)
241
+ : s2 <= 1 ? ddLog([em1, 0])
242
+ : ddAdd(s2dd, [Math.log(-Math.expm1(-s2)), 0]);
243
+ const half = ddAdd(s2dd, logEm1);
244
+ const logSd = ddAdd([meanlog, 0], [half[0] / 2, half[1] / 2]);
245
+ const keepSd = Number.isFinite(rootEm1) && expHalf >= MIN_NORMAL && expHalf < Infinity;
246
+ return {
247
+ ...result,
248
+ variance: ddExp([2 * logSd[0], 2 * logSd[1]])[0],
249
+ sd: keepSd ? result.sd : ddExp(logSd)[0],
250
+ };
99
251
  }
100
252
  case "unif": {
101
253
  const { min = 0, max = 1 } = P;
102
254
  if (!(Number.isFinite(min) && Number.isFinite(max) && min < max))
103
255
  return NAN;
104
- const m = min + (max - min) / 2;
105
- return make(m, (max - min) ** 2 / 12, m, NaN, 0, -1.2);
256
+ const m = Number.isFinite(max - min) ? min + (max - min) / 2 : midpoint(min, max);
257
+ const w = max - min;
258
+ return make(m, rescaled(w ** 2 / 12, (x) => x ** 2 / 12, [w, 2]), m, NaN, 0, -1.2, (max / 2 - min / 2) * (2 / Math.sqrt(12)));
106
259
  }
107
260
  case "exp": {
108
261
  const { rate = 1 } = P;
109
262
  if (!(rate > 0 && Number.isFinite(rate)))
110
263
  return NAN;
111
- return make(1 / rate, 1 / (rate * rate), Math.LN2 / rate, 0, 2, 6);
264
+ return make(1 / rate, rescaled(1 / (rate * rate), (x) => 1 / (x * x), [rate, -2]), Math.LN2 / rate, 0, 2, 6, 1 / rate);
112
265
  }
113
266
  case "gamma": {
114
267
  const k = P.shape ?? NaN;
115
- const scale = has(P, "scale") ? P.scale : 1 / (P.rate ?? 1);
268
+ // (rate and scale as dgamma: both only with scale = 1 / rate, otherwise invalid; the scale was taken and the rate
269
+ // ignored; issue #245)
270
+ let scale;
271
+ try {
272
+ scale = gammaScale({ ...(has(P, "rate") && { rate: P.rate }), ...(has(P, "scale") && { scale: P.scale }) });
273
+ }
274
+ catch {
275
+ return NAN;
276
+ }
116
277
  if (!(k > 0 && Number.isFinite(k) && scale > 0 && Number.isFinite(scale)))
117
278
  return NAN;
118
- return make(k * scale, k * scale * scale, qgamma(0.5, k, { scale }), k >= 1 ? (k - 1) * scale : 0, 2 / Math.sqrt(k), 6 / k);
279
+ return make(k * scale, k * scale * scale, qgamma(0.5, k, { scale }), k >= 1 ? (k - 1) * scale : 0, 2 / Math.sqrt(k), 6 / k, Math.sqrt(k) * scale);
119
280
  }
120
281
  case "chisq": {
121
282
  const df = P.df ?? NaN;
122
283
  if (!(df > 0 && Number.isFinite(df)))
123
284
  return NAN;
124
- return make(df, 2 * df, qchisq(0.5, df), Math.max(df - 2, 0), Math.sqrt(8 / df), 12 / df);
285
+ return make(df, 2 * df, qchisq(0.5, df), Math.max(df - 2, 0), Math.sqrt(8 / df), 12 / df, Math.SQRT2 * Math.sqrt(df));
125
286
  }
126
287
  case "beta": {
127
288
  const a = P.shape1 ?? NaN;
@@ -131,12 +292,40 @@ export function distSummary(distribution, params = {}) {
131
292
  const s = a + b;
132
293
  let mode;
133
294
  if (a > 1 && b > 1)
134
- mode = (a - 1) / (s - 2);
295
+ mode = Number.isFinite(s) ? (a - 1) / (s - 2) : (a - 1) / 2 / ((a - 1) / 2 + (b - 1) / 2);
135
296
  else if ((a === 1 && b === 1) || (a < 1 && b < 1))
136
297
  mode = NaN;
137
298
  else
138
299
  mode = a <= 1 && b >= 1 ? 0 : 1;
139
- return make(a / s, (a * b) / (s * s * (s + 1)), qbeta(0.5, a, b), mode, (2 * (b - a) * Math.sqrt(s + 1)) / ((s + 2) * Math.sqrt(a * b)), (6 * ((a - b) ** 2 * (s + 1) - a * b * (s + 2))) / (a * b * (s + 2) * (s + 3)));
300
+ const median = qbeta(0.5, a, b);
301
+ if (!Number.isFinite(s)) {
302
+ // a + b overflows: from the halved shapes, p = a / (a + b), q = b / (a + b) and h = (a + b) / 2, with s + 1, s + 2
303
+ // and s + 3 equal to s (beta(1e308, 1e308) had mean 0, mode 0 and variance 0)
304
+ const h = a / 2 + b / 2;
305
+ const pa = a / 2 / h;
306
+ const pb = b / 2 / h;
307
+ return make(pa, (pa * pb) / h / 2, median, mode, (2 * (pb - pa)) / (Math.sqrt(pa) * Math.sqrt(pb) * Math.SQRT2 * Math.sqrt(h)), (3 * ((pa - pb) ** 2 / (pa * pb) - 1)) / h, (Math.sqrt(pa) * Math.sqrt(pb)) / Math.sqrt(h) / Math.SQRT2);
308
+ }
309
+ const ab = a * b;
310
+ // Where a b overflows or underflows (shapes beyond 1e154 or below 1e-154), the moments in p = a / s and q = b / s
311
+ // (numerators and denominators divided by s^2; beta(1e200, 1e200) had kurtosis NaN)
312
+ const inRange = ab >= MIN_NORMAL && ab < Infinity;
313
+ const pa = a / s;
314
+ const pb = b / s;
315
+ // The closed forms also where a b is in range but their numerator or denominator is not (unbalanced or large
316
+ // shapes: (a - b)^2 and a b (s + 2)(s + 3) overflow, beta(1e-3, 1e155) had kurtosis NaN for 6000 and
317
+ // beta(1e100, 1e100) 0 for -3e-100; issue #385)
318
+ const direct = (num, den) => inRange && (num === 0 || Math.abs(num) >= MIN_NORMAL) && Math.abs(num) < Infinity && den >= MIN_NORMAL && den < Infinity
319
+ ? num / den
320
+ : undefined;
321
+ return make(pa, betaVariance(a, b, s), median, mode, direct(2 * (b - a) * Math.sqrt(s + 1), (s + 2) * Math.sqrt(ab)) ??
322
+ (2 * (pb - pa) * Math.sqrt(s + 1)) / ((s + 2) * Math.sqrt(pa * pb)), direct(6 * ((a - b) ** 2 * (s + 1) - ab * (s + 2)), ab * (s + 2) * (s + 3)) ??
323
+ (6 * ((pa - pb) ** 2 * ((s + 1) / (s + 2)) - pa * pb)) / (pa * pb * (s + 3)),
324
+ // (where a / s or b / s is below the normal range, the square roots taken before the ratios: beta(1e-308, 1e154)
325
+ // had sd 0 for 1e-308; issue #241)
326
+ pa >= MIN_NORMAL && pb >= MIN_NORMAL
327
+ ? (Math.sqrt(pa) * Math.sqrt(pb)) / Math.sqrt(s + 1)
328
+ : ((Math.sqrt(a) / Math.sqrt(s)) * (Math.sqrt(b) / Math.sqrt(s))) / Math.sqrt(s + 1));
140
329
  }
141
330
  case "t": {
142
331
  const df = P.df ?? NaN;
@@ -152,12 +341,55 @@ export function distSummary(distribution, params = {}) {
152
341
  if (!(d1 > 0 && d2 > 0 && Number.isFinite(d1) && Number.isFinite(d2)))
153
342
  return NAN;
154
343
  const mean = d2 > 2 ? d2 / (d2 - 2) : NaN;
155
- const variance = d2 > 4 ? (2 * d2 * d2 * (d1 + d2 - 2)) / (d1 * (d2 - 2) ** 2 * (d2 - 4)) : d2 > 2 ? Infinity : NaN;
156
- const skewness = d2 > 6 ? ((2 * d1 + d2 - 2) * Math.sqrt(8 * (d2 - 4))) / ((d2 - 6) * Math.sqrt(d1 * (d1 + d2 - 2))) : NaN;
157
- const kurtosis = d2 > 8
158
- ? (12 * (d1 * (5 * d2 - 22) * (d1 + d2 - 2) + (d2 - 4) * (d2 - 2) ** 2)) / (d1 * (d2 - 6) * (d2 - 8) * (d1 + d2 - 2))
159
- : NaN;
160
- return make(mean, variance, qf(0.5, d1, d2), d1 > 2 ? ((d1 - 2) / d1) * (d2 / (d2 + 2)) : 0, skewness, kurtosis);
344
+ // Each closed form where its numerator and denominator are normal numbers (the same bits as before); otherwise
345
+ // from ratios that stay in range, with t = d1 + d2 - 2 halved (df1 = df2 = 1e200 gave variance NaN, sd 0 and
346
+ // skewness 0; 1e308 NaN throughout; issue #235)
347
+ const inRange = (x) => x >= MIN_NORMAL && x < Infinity;
348
+ const t = d1 + d2 - 2;
349
+ const th = d1 / 2 + d2 / 2 - 1; // t / 2
350
+ const r = d2 / (d2 - 2);
351
+ const u = (d2 - 2) / d1; // t / d1 - 1
352
+ const w = (d2 - 2) / (d2 - 4);
353
+ let variance = d2 > 4 ? NaN : d2 > 2 ? Infinity : NaN;
354
+ let sd = variance;
355
+ if (d2 > 4) {
356
+ const num = 2 * d2 * d2 * t;
357
+ const den = d1 * (d2 - 2) ** 2 * (d2 - 4);
358
+ // 2 r^2 (t / d1) / (d2 - 4) with t / d1 = 1 + u; where u overflows, 2 r^2 (1 / (d2 - 4) + w / d1)
359
+ variance = inRange(num) && inRange(den) ? num / den : Number.isFinite(u) ? (2 * r * r * (1 + u)) / (d2 - 4) : 2 * r * r * (1 / (d2 - 4) + w / d1);
360
+ // (the standard deviation from the square roots of the factors, where the variance overflows)
361
+ const sNum = Math.SQRT2 * d2 * Math.sqrt(t);
362
+ const sDen = Math.sqrt(d1) * (d2 - 2) * Math.sqrt(d2 - 4);
363
+ sd =
364
+ inRange(sNum) && inRange(sDen)
365
+ ? sNum / sDen
366
+ : Number.isFinite(u)
367
+ ? Math.SQRT2 * r * (Math.sqrt(1 + u) / Math.sqrt(d2 - 4))
368
+ : Math.SQRT2 * r * (Math.sqrt(w) / Math.sqrt(d1));
369
+ }
370
+ let skewness = NaN;
371
+ if (d2 > 6) {
372
+ const num = (2 * d1 + d2 - 2) * Math.sqrt(8 * (d2 - 4));
373
+ const den = (d2 - 6) * Math.sqrt(d1 * t);
374
+ // (d1 + t) / sqrt(d1 t) = sqrt(d1 / t) + sqrt(t / d1)
375
+ const sq1 = Math.sqrt(d1);
376
+ const sqt = Math.sqrt(th) * Math.SQRT2;
377
+ const x = (Math.sqrt(8) * Math.sqrt(d2 - 4)) / (d2 - 6);
378
+ skewness = inRange(num) && inRange(den) ? num / den : (sq1 / sqt) * x + (sqt * x) / sq1;
379
+ }
380
+ let kurtosis = NaN;
381
+ if (d2 > 8) {
382
+ const num = 12 * (d1 * (5 * d2 - 22) * t + (d2 - 4) * (d2 - 2) ** 2);
383
+ const den = d1 * (d2 - 6) * (d2 - 8) * t;
384
+ // 12 ((5 d2 - 22) / ((d2 - 6)(d2 - 8)) + (d2 - 4)(d2 - 2)^2 / (d1 (d2 - 6)(d2 - 8) t))
385
+ kurtosis =
386
+ inRange(num) && inRange(den)
387
+ ? num / den
388
+ : 12 *
389
+ (((5 - 22 / d2) * (d2 / (d2 - 6))) / (d2 - 8) +
390
+ ((d2 - 4) / (d2 - 6)) * ((d2 - 2) / (d2 - 8)) * ((d2 / 2 - 1) / th / d1));
391
+ }
392
+ return make(mean, variance, qf(0.5, d1, d2), d1 > 2 ? ((d1 - 2) / d1) * (d2 / (d2 + 2)) : 0, skewness, kurtosis, sd);
161
393
  }
162
394
  case "cauchy": {
163
395
  const { location = 0, scale = 1 } = P;
@@ -171,14 +403,24 @@ export function distSummary(distribution, params = {}) {
171
403
  if (!(k > 0 && Number.isFinite(k) && lam > 0 && Number.isFinite(lam)))
172
404
  return NAN;
173
405
  const mean = gammaFn(1 + 1 / k);
174
- const s = shape((x) => dweibull1(x, k, 1, false), mean, 0, Infinity);
175
- return make(lam * mean, lam * lam * s.variance, qweibull(0.5, k, { scale: lam }), k > 1 ? lam * Math.pow((k - 1) / k, 1 / k) : 0, s.skewness, s.kurtosis);
406
+ // X^k ~ Exp(1)
407
+ const big = k > LARGE_SHAPE ? expShape(k, [{ logE: Math.log, w: (e) => Math.exp(-e), upper: Infinity, tAt: Math.exp }]) : undefined;
408
+ if (big !== undefined) {
409
+ const sd = lam * (Math.sqrt(big.variance) / k);
410
+ const median = qweibull(0.5, k, { scale: lam });
411
+ return make(lam * mean, sd * sd, median, lam * Math.pow((k - 1) / k, 1 / k), big.skewness, big.kurtosis, sd);
412
+ }
413
+ // E[X^r] = Gamma(1 + r/k) for scale 1: used when the integrals do not converge (small shapes, heavy tails)
414
+ const si = shape((x) => dweibull1(x, k, 1, false), mean, 0, Infinity);
415
+ const s = si.ok ? si : fromLogRawMoments([1, 2, 3, 4].map((r) => lgamma(1 + r / k)));
416
+ return make(lam * mean, rescaled(lam * lam * s.variance, (x) => x * x * s.variance, [lam, 2]), qweibull(0.5, k, { scale: lam }), k > 1 ? lam * Math.pow((k - 1) / k, 1 / k) : 0, s.skewness, s.kurtosis, lam * Math.sqrt(s.variance));
176
417
  }
177
418
  case "logis": {
178
419
  const { location = 0, scale = 1 } = P;
179
420
  if (!(Number.isFinite(location) && scale > 0 && Number.isFinite(scale)))
180
421
  return NAN;
181
- return make(location, (scale * scale * Math.PI * Math.PI) / 3, location, location, 0, 1.2);
422
+ const v = (scale * scale * Math.PI * Math.PI) / 3;
423
+ return make(location, rescaled(v, (x) => (x * x * Math.PI * Math.PI) / 3, [scale, 2]), location, location, 0, 1.2, (scale * Math.PI) / Math.sqrt(3));
182
424
  }
183
425
  case "binom": {
184
426
  const n = P.size ?? NaN;
@@ -186,11 +428,16 @@ export function distSummary(distribution, params = {}) {
186
428
  if (!(Number.isInteger(n) && n >= 0 && p >= 0 && p <= 1))
187
429
  return NAN;
188
430
  const q = 1 - p;
431
+ // (a point mass: no skewness or kurtosis)
432
+ const point = n === 0 || p === 0 || p === 1;
189
433
  // P(x) >= P(x - 1) exactly when x <= (n + 1) p
190
- return make(n * p, n * p * q, qbinom(0.5, n, p), Math.min(n, floorProduct(n + 1, p)), (q - p) / Math.sqrt(n * p * q), (1 - 6 * p * q) / (n * p * q));
434
+ return make(n * p, n * p * q, qbinom(0.5, n, p), Math.min(n, floorProduct(n + 1, p)), point ? NaN : (q - p) / Math.sqrt(n * p * q), point ? NaN : (1 - 6 * p * q) / (n * p * q));
191
435
  }
192
436
  case "pois": {
193
437
  const lambda = P.lambda ?? NaN;
438
+ // (lambda = 0 is the point mass at 0, as in dpois, ppois and qpois; issue #379)
439
+ if (lambda === 0)
440
+ return POINT_AT_0;
194
441
  if (!(lambda > 0 && Number.isFinite(lambda)))
195
442
  return NAN;
196
443
  return make(lambda, lambda, qpois(0.5, lambda), Math.floor(lambda), 1 / Math.sqrt(lambda), 1 / lambda);
@@ -200,28 +447,67 @@ export function distSummary(distribution, params = {}) {
200
447
  if (!(p > 0 && p <= 1))
201
448
  return NAN;
202
449
  const q = 1 - p;
203
- return make(q / p, q / (p * p), qgeom(0.5, p), 0, (2 - p) / Math.sqrt(q), 6 + (p * p) / q);
450
+ // (p = 1 is a point mass at 0: no skewness or kurtosis)
451
+ return make(q / p, q / (p * p), qgeom(0.5, p), 0, p === 1 ? NaN : (2 - p) / Math.sqrt(q), p === 1 ? NaN : 6 + (p * p) / q, Math.sqrt(q) / p);
204
452
  }
205
453
  case "nbinom": {
206
454
  const r = P.size ?? NaN;
455
+ // (size = 0 is the point mass at 0, as in dnbinom, pnbinom and qnbinom, with a valid prob or mu; before p = size /
456
+ // (size + mu), which is 0 or 0/0 there; issue #379)
457
+ if (r === 0)
458
+ return (has(P, "mu") ? P.mu >= 0 && P.mu < Infinity : P.prob > 0 && P.prob <= 1) ? POINT_AT_0 : NAN;
207
459
  if (!(r > 0 && Number.isFinite(r)))
208
460
  return NAN;
209
- const p = has(P, "mu") ? r / (r + P.mu) : (P.prob ?? NaN);
461
+ // (where size + mu overflows, from the halved parameters: size = mu = 1e308 gave p = 0 and NaN throughout; issue #236)
462
+ const p = has(P, "mu") ? (Number.isFinite(r + P.mu) ? r / (r + P.mu) : r / 2 / (r / 2 + P.mu / 2)) : (P.prob ?? NaN);
210
463
  if (!(p > 0 && p <= 1))
211
464
  return NAN;
212
465
  const q = 1 - p;
213
466
  const opts = has(P, "mu") ? { mu: P.mu } : { prob: p };
214
467
  // P(x) >= P(x - 1) exactly when x p <= (r - 1)(1 - p), i.e. (x + r - 1) p <= r - 1 (with mu: x r <= (r - 1) mu)
215
- const ok = (x) => has(P, "mu") ? productAtMost([x, 0], r, (r - 1) * P.mu) : productAtMost(ddAdd([r - 1, 0], [x, 0]), p, r - 1);
468
+ // Beyond 2^53, r - 1 rounds to r (an integer mu passed as its own mode, floor(mu - mu / r) = mu - 1) and
469
+ // (r - 1) mu can overflow, the bound Infinity passing every step (size 4.3e305, mu 1.8e11 did not end): there
470
+ // the test in exact integers, as r is one (issue #236 follow-up 3)
471
+ const ok = (x) => has(P, "mu")
472
+ ? r > 2 ** 53
473
+ ? exactModeTest(x, r, P.mu)
474
+ : productAtMost([x, 0], r, (r - 1) * P.mu)
475
+ : productAtMost(ddAdd([r - 1, 0], [x, 0]), p, r - 1);
216
476
  let mode = 0;
217
477
  if (r > 1) {
218
- mode = Math.max(0, Math.floor(((r - 1) * q) / p) - 1);
219
- while (ok(mode + 1))
220
- mode++;
221
- while (mode > 0 && !ok(mode))
222
- mode--;
478
+ const guess = Math.floor(((r - 1) * q) / p);
479
+ // With mu much smaller than size, q = 1 - p loses its digits (0 where p rounds to 1) and the guess is far below
480
+ // the mode, which the search then walked one by one (size 1e100, mu 1e30 did not end; issue #236 follow-up):
481
+ // there the guess from (r - 1) / r mu. The search ends at the same mode from either start.
482
+ const near = has(P, "mu") && guess < 2 ** 53 ? Math.floor(((r - 1) / r) * P.mu) : guess;
483
+ // Beyond 2^53 the integers are not all doubles (mode + 1 = mode, and the search did not end): the rounded value
484
+ if (!(guess < 2 ** 53))
485
+ mode = guess;
486
+ else if (!(near < 2 ** 53))
487
+ mode = near;
488
+ else {
489
+ mode = Math.max(0, near - 1);
490
+ while (ok(mode + 1))
491
+ mode++;
492
+ while (mode > 0 && !ok(mode))
493
+ mode--;
494
+ }
223
495
  }
224
- return make((r * q) / p, (r * q) / (p * p), qnbinom(0.5, r, opts), mode, (2 - p) / Math.sqrt(r * q), 6 / r + (p * p) / (r * q));
496
+ const mu = P.mu;
497
+ if (mu !== undefined && mu > 0 && mu / r < 2 ** -26) {
498
+ // With mu far below size, q = 1 - p keeps only the digits of p's rounding (size 1e10, mu 1 gave a mean 8e-8
499
+ // off; size 1e100, mu 1e30 a mean 0 and NaN skewness): the moments directly in mu and t = mu / size, as
500
+ // mu (1 + t), (1 + 2t) / sqrt(mu (1 + t)) and 6 / size + 1 / (mu (1 + t)) (issue #236 follow-up 2). The
501
+ // products of the closed forms overflow or underflow (size 1e308 with mu 1), these do not.
502
+ const t = mu / r;
503
+ const variance = mu + mu * t;
504
+ // (sqrt(mu) sqrt(1 + t) where the variance is subnormal)
505
+ const sd = variance >= MIN_NORMAL ? Math.sqrt(variance) : Math.sqrt(mu) * Math.sqrt(1 + t);
506
+ return make(mu, variance, qnbinom(0.5, r, opts), mode, (1 + 2 * t) / sd, 6 / r + 1 / variance, sd);
507
+ }
508
+ return make((r * q) / p, rescaled((r * q) / (p * p), (x, y) => (x * q) / (y * y), [r, 1], [p, -2]), qnbinom(0.5, r, opts), mode,
509
+ // (p = 1 is a point mass at 0: no skewness or kurtosis)
510
+ p === 1 ? NaN : (2 - p) / Math.sqrt(r * q), p === 1 ? NaN : 6 / r + (p * p) / (r * q), (Math.sqrt(r) * Math.sqrt(q)) / p);
225
511
  }
226
512
  case "hyper": {
227
513
  const m = P.m ?? NaN;
@@ -230,63 +516,167 @@ export function distSummary(distribution, params = {}) {
230
516
  if (!([m, n, k].every((v) => Number.isInteger(v) && v >= 0) && k <= m + n))
231
517
  return NAN;
232
518
  const N = m + n;
233
- const mo = Math.floor(((k + 1) * (m + 1)) / (N + 2));
234
- const kurt = ((N - 1) * N * N * (N * (N + 1) - 6 * m * n - 6 * k * (N - k)) + 6 * k * m * n * (N - k) * (5 * N - 6)) /
235
- (k * m * n * (N - k) * (N - 2) * (N - 3));
236
- return make((k * m) / N, (((k * m) / N) * (n / N) * (N - k)) / (N - 1), qhyper(0.5, m, n, k), mo, ((N - 2 * m) * Math.sqrt(N - 1) * (N - 2 * k)) / (Math.sqrt(k * m * n * (N - k)) * (N - 2)), kurt);
519
+ // Where (k + 1)(m + 1) overflows, the floor of the exact quotient in integers, rounded to a double (beyond 2^53,
520
+ // as the nbinom mode); k m / N and the variance from the ratio m / N where the products overflow (m = n = k =
521
+ // 1e200 gave mean, variance and mode Infinity; issue #237)
522
+ const moProduct = (k + 1) * (m + 1);
523
+ const mo = Number.isFinite(moProduct)
524
+ ? Math.floor(moProduct / (N + 2))
525
+ : Number(((BigInt(k) + 1n) * (BigInt(m) + 1n)) / (BigInt(m) + BigInt(n) + 2n));
526
+ // a point mass (k = 0, m = 0, n = 0 or k = N) has variance 0 and the mean k m / N, 0 for N = 0 (the formulas gave
527
+ // 0/0 for N = 0 and N = 1; issue #19)
528
+ const point = k === 0 || m === 0 || n === 0 || k === N;
529
+ const mean = N === 0 ? 0 : Number.isFinite(k * m) ? (k * m) / N : k * (m / N);
530
+ const vPlain = ((mean * (n / N)) * (N - k)) / (N - 1);
531
+ const variance = point ? 0 : Number.isFinite(vPlain) ? vPlain : mean * (n / N) * ((N - k) / (N - 1));
532
+ let skewness;
533
+ let kurt;
534
+ if (k === 0 || m === 0 || n === 0 || k === N) {
535
+ // a point mass: no skewness or kurtosis
536
+ skewness = NaN;
537
+ kurt = NaN;
538
+ }
539
+ else if (N <= 3) {
540
+ // the closed forms divide by N - 2 and N - 3: the central moments over the (at most two-point) support
541
+ const c = [2, 3, 4].map((r) => {
542
+ let s = 0;
543
+ for (let x = Math.max(0, k - n); x <= Math.min(k, m); x++)
544
+ s += dhyper1(x, m, n, k, false) * (x - mean) ** r;
545
+ return s;
546
+ });
547
+ skewness = c[1] / c[0] ** 1.5;
548
+ kurt = c[2] / (c[0] * c[0]) - 3;
549
+ }
550
+ else {
551
+ skewness = ((N - 2 * m) * Math.sqrt(N - 1) * (N - 2 * k)) / (Math.sqrt(k * m * n * (N - k)) * (N - 2));
552
+ const num = (N - 1) * N * N * (N * (N + 1) - 6 * m * n - 6 * k * (N - k)) + 6 * k * m * n * (N - k) * (5 * N - 6);
553
+ const den = k * m * n * (N - k) * (N - 2) * (N - 3);
554
+ if (Number.isFinite(num) && Number.isFinite(den))
555
+ kurt = num / den;
556
+ else {
557
+ // the products overflow: numerator and denominator divided by N^5, in p = m / N, q = n / N, f = k / N and
558
+ // g = (N - k) / N (m = n = k = 1e150 gave NaN for about -1e-150; issue #244)
559
+ const pq = (m / N) * (n / N);
560
+ const fg = (k / N) * ((N - k) / N);
561
+ const a = 1 + 1 / N - 6 * pq - 6 * fg;
562
+ kurt = ((1 - 1 / N) * a + 6 * pq * fg * (5 - 6 / N)) / (k * pq * ((N - k) / N) * ((1 - 2 / N) * (1 - 3 / N)));
563
+ }
564
+ }
565
+ return make(mean, variance, qhyper(0.5, m, n, k), mo, skewness, kurt);
237
566
  }
238
567
  case "invgamma": {
239
568
  const a = P.alpha ?? NaN;
240
569
  const b = P.beta ?? 1;
241
570
  if (!(a > 0 && Number.isFinite(a) && b > 0 && Number.isFinite(b)))
242
571
  return NAN;
243
- return make(a > 1 ? b / (a - 1) : Infinity, a > 2 ? (b * b) / ((a - 1) ** 2 * (a - 2)) : a > 1 ? Infinity : NaN, qinvgamma(0.5, a, { beta: b }), b / (a + 1), a > 3 ? (4 * Math.sqrt(a - 2)) / (a - 3) : NaN, a > 4 ? (30 * a - 66) / ((a - 3) * (a - 4)) : NaN);
572
+ // Where b^2, (a - 1)^2 (a - 2), (a - 1) sqrt(a - 2) or (a - 3)(a - 4) leave the range, from r = b / (a - 1) and
573
+ // ratios of a (alpha = beta = 1e308 gave variance NaN, sd 0 and kurtosis NaN; issue #238)
574
+ const r = b / (a - 1);
575
+ const b2 = b * b;
576
+ const vDen = (a - 1) ** 2 * (a - 2);
577
+ const sdDen = (a - 1) * Math.sqrt(a - 2);
578
+ const kurt = (30 * a - 66) / ((a - 3) * (a - 4));
579
+ return make(a > 1 ? r : Infinity, a > 2 ? (b2 >= MIN_NORMAL && b2 < Infinity && vDen < Infinity ? b2 / vDen : r * (r / (a - 2))) : a > 1 ? Infinity : NaN, qinvgamma(0.5, a, { beta: b }), b / (a + 1), a > 3 ? (4 * Math.sqrt(a - 2)) / (a - 3) : NaN, a > 4 ? (kurt > 0 && kurt < Infinity ? kurt : ((30 - 66 / a) / (a - 3)) * (a / (a - 4))) : NaN, a > 2 ? (sdDen < Infinity ? b / sdDen : r / Math.sqrt(a - 2)) : undefined);
244
580
  }
245
581
  case "kumar": {
246
582
  const a = P.a ?? NaN;
247
583
  const b = P.b ?? NaN;
248
584
  if (!(a > 0 && b > 0 && Number.isFinite(a) && Number.isFinite(b)))
249
585
  return NAN;
250
- // mean b B(1 + 1/a, b)
251
- const mean = b * Math.exp(lbeta(1 + 1 / a, b));
586
+ // X = c (b W)^(1/a) with c = b^(-1/a), W = X^a ~ Beta(1, b): for a > 100, the moments in T = a (X / c - 1) over
587
+ // e = b W, density (1 - e/b)^(b - 1) on (0, b). b >= 1: one piece in e (beyond 1500 the density is below
588
+ // e^-1500). b < 1: the density diverges at e = b, so (b/2, b) is taken in r = b - e, the density
589
+ // (r/b)^(b - 1) by its total 2^-b and the integral of the differences from r = 0 (in e alone, a = 150, b = 0.1
590
+ // lost 3e-10 of the kurtosis)
591
+ const inE = (upper) => ({
592
+ logE: Math.log,
593
+ w: (e) => (e >= b ? 0 : Math.exp((b - 1) * Math.log1p(-e / b))),
594
+ upper,
595
+ tAt: Math.exp,
596
+ });
597
+ const nearB = {
598
+ logE: (r) => Math.log(b - r),
599
+ w: (r) => Math.exp((b - 1) * Math.log(r / b)),
600
+ upper: b / 2,
601
+ tAt: (le) => b - Math.exp(le),
602
+ mass: Math.pow(0.5, b),
603
+ };
604
+ const big = a > LARGE_SHAPE ? expShape(a, b >= 1 ? [inE(Math.min(b, 1500))] : [inE(b / 2), nearB]) : undefined;
605
+ const c = big === undefined ? NaN : Math.exp(-Math.log(b) / a);
606
+ // mean b B(1 + 1/a, b); for a > 100, c (1 + E[T] / a) (b B(1 + 1/a, b) was 1e-14 off at a = b = 1e100)
607
+ const mean = big === undefined ? b * Math.exp(lbeta(1 + 1 / a, b)) : c * (1 + big.meanT / a);
252
608
  // over the density, or over u = F(x) when the density diverges at 1 (b < 1: there the quantile is smooth)
253
- const s = b < 1
254
- ? central((u) => qkumar1(u, a, b, true, false), () => 1, mean, pkumar1(mean, a, b, true, false), 0, 1)
255
- : shape((x) => dkumar1(x, a, b, false), mean, 0, 1);
609
+ const si = big !== undefined
610
+ ? big
611
+ : b < 1
612
+ ? central((u) => qkumar1(u, a, b, true, false), () => 1, mean, pkumar1(mean, a, b, true, false), 0, 1)
613
+ : shape((x) => dkumar1(x, a, b, false), mean, 0, 1);
614
+ // E[X^r] = b B(1 + r/a, b): used when the integrals do not converge
615
+ const s = si.ok ? si : fromLogRawMoments([1, 2, 3, 4].map((r) => Math.log(b) + lbeta(1 + r / a, b)));
616
+ // the sd in T's units (the variance of X underflows for a = 1e308: sd 1.28e-308)
617
+ const sd = big === undefined ? undefined : c * (Math.sqrt(big.variance) / a);
256
618
  let mode;
257
- if (a >= 1 && b >= 1)
258
- mode = a === 1 && b === 1 ? NaN : Math.pow((a - 1) / (a * b - 1), 1 / a);
619
+ // ((a - 1) / (a b - 1))^(1/a); where a b overflows (a b - 1 is a b there), as ((a - 1) / a)^(1/a) b^(-1/a)
620
+ // (a = b = 1e200 gave 0 for 1; issue #239)
621
+ if (a >= 1 && b >= 1) {
622
+ if (a === 1 && b === 1)
623
+ mode = NaN;
624
+ else
625
+ mode = Number.isFinite(a * b) ? Math.pow((a - 1) / (a * b - 1), 1 / a) : Math.pow((a - 1) / a, 1 / a) * Math.pow(b, -1 / a);
626
+ }
259
627
  else if (a < 1 && b < 1)
260
628
  mode = NaN;
261
629
  else
262
630
  mode = a < 1 ? 0 : 1;
263
- return make(mean, s.variance, qkumar(0.5, a, b), mode, s.skewness, s.kurtosis);
631
+ return make(mean, sd === undefined ? s.variance : sd * sd, qkumar(0.5, a, b), mode, s.skewness, s.kurtosis, sd);
264
632
  }
265
633
  case "pareto": {
266
634
  const { a = 1, b = 1 } = P;
267
635
  if (!(a > 0 && Number.isFinite(a) && b > 0 && Number.isFinite(b)))
268
636
  return NAN;
269
- return make(a > 1 ? (a * b) / (a - 1) : Infinity, a > 2 ? (b * b * a) / ((a - 1) ** 2 * (a - 2)) : a > 1 ? Infinity : NaN, b * Math.pow(2, 1 / a), b, a > 3 ? ((2 * (1 + a)) / (a - 3)) * Math.sqrt((a - 2) / a) : NaN, a > 4 ? (6 * (a ** 3 + a * a - 6 * a - 2)) / (a * (a - 3) * (a - 4)) : NaN);
637
+ // Each moment from the closed form, or where an intermediate product overflows (a b, b² a, a³, 2 (1 + a), b √a:
638
+ // a = b = 1e308 gave mean Inf, variance NaN, kurtosis NaN; issue #34) from ratios in which the powers cancel
639
+ const orElse = (v, alt) => (Number.isFinite(v) ? v : alt());
640
+ const r = b / (a - 1);
641
+ return make(a > 1 ? orElse((a * b) / (a - 1), () => b * (a / (a - 1))) : Infinity, a > 2 ? orElse((b * b * a) / ((a - 1) ** 2 * (a - 2)), () => r * r * (a / (a - 2))) : a > 1 ? Infinity : NaN, b * Math.pow(2, 1 / a), b, a > 3 ? orElse(((2 * (1 + a)) / (a - 3)) * Math.sqrt((a - 2) / a), () => 2 * ((1 + a) / (a - 3)) * Math.sqrt((a - 2) / a)) : NaN, a > 4
642
+ ? orElse((6 * (a ** 3 + a * a - 6 * a - 2)) / (a * (a - 3) * (a - 4)), () => (6 * (1 + 1 / a - 6 / (a * a) - 2 / a ** 3)) / ((1 - 3 / a) * (1 - 4 / a)))
643
+ : NaN, a > 2 ? orElse((b * Math.sqrt(a)) / ((a - 1) * Math.sqrt(a - 2)), () => r * Math.sqrt(a / (a - 2))) : undefined);
270
644
  }
271
645
  case "triang": {
272
646
  const { a = -1, b = 1 } = P;
273
- const c = P.c ?? (a + b) / 2;
647
+ const c = P.c ?? midpoint(a, b);
274
648
  if (!(Number.isFinite(a) && Number.isFinite(b) && a < b && a <= c && c <= b))
275
649
  return NAN;
276
- const q = a * a + b * b + c * c - a * b - a * c - b * c;
277
- return make((a + b + c) / 3, q / 18, qtriang(0.5, { a, b, c }), c, (Math.SQRT2 * (a + b - 2 * c) * (2 * a - b - c) * (a - 2 * b + c)) / (5 * q ** 1.5), -0.6);
650
+ // q = a² + b² + c² - ab - ac - bc as (b - a)(b - c) + (c - a)², whose terms are all non-negative: the
651
+ // expanded form cancels when the location is large against the width ((1e10, 1e10 + 1, 1e10 + 0.25) gave the
652
+ // variance 910 for 0.045) and overflows to Inf - Inf near the top of the range (issue #243). The skewness's
653
+ // numerator (a + b - 2c)(2a - b - c)(a - 2b + c) is (w - v)(u + v)(u + w) in the same differences
654
+ const e = Math.floor(Math.log2(Math.max(Math.abs(a), Math.abs(b), Math.abs(c))));
655
+ // from the parameters divided by 2^e where b - a overflows, the powers of the parameters' scale could
656
+ // overflow or underflow (the largest outside [2^-300, 2^300]) or those of the width could underflow (below
657
+ // 2^-290: q^1.5 fell onto the subnormals); otherwise the products are in range
658
+ const scaled = !Number.isFinite(b - a) || e < -300 || e >= 300 || b - a < 2 ** -290;
659
+ const [x, y, z] = scaled ? [a, b, c].map((v) => ldexp(v, -e)) : [a, b, c];
660
+ const u = y - x;
661
+ const v = z - x;
662
+ const w = y - z;
663
+ const q = u * w + v * v;
664
+ return make(Number.isFinite(a + b + c) ? (a + b + c) / 3 : a / 3 + b / 3 + c / 3, scaled ? ldexp(q / 18, 2 * e) : q / 18, qtriang(0.5, { a, b, c }), c, (Math.SQRT2 * (w - v) * (u + v) * (u + w)) / (5 * q ** 1.5), -0.6, scaled ? ldexp(Math.sqrt(q / 18), e) : Math.sqrt(q / 18));
278
665
  }
279
666
  case "laplace": {
280
667
  const { mu = 0, sigma = 1 } = P;
281
668
  if (!(Number.isFinite(mu) && sigma > 0 && Number.isFinite(sigma)))
282
669
  return NAN;
283
- return make(mu, 2 * sigma * sigma, mu, mu, 0, 3);
670
+ return make(mu, 2 * sigma * sigma, mu, mu, 0, 3, Math.SQRT2 * sigma);
284
671
  }
285
672
  case "arcsine": {
286
673
  const { a = 0, b = 1 } = P;
287
674
  if (!(Number.isFinite(a) && Number.isFinite(b) && a < b))
288
675
  return NAN;
289
- return make(a + (b - a) / 2, (b - a) ** 2 / 8, qarcsine(0.5, { a, b }), NaN, 0, -1.5);
676
+ // symmetric: the median is the mean (qarcsine(0.5) rounds to 1e-16 of the width); b - a may overflow
677
+ const mean = Number.isFinite(b - a) ? a + (b - a) / 2 : midpoint(a, b);
678
+ const w = b - a;
679
+ return make(mean, rescaled(w ** 2 / 8, (x) => x ** 2 / 8, [w, 2]), mean, NaN, 0, -1.5, (b / 2 - a / 2) / Math.SQRT2);
290
680
  }
291
681
  }
292
682
  throw new RangeError(`unknown distribution '${String(distribution)}'`);