@numero-uno-jpn/rstats 0.15.3 → 0.17.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 (322) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/README.ja.md +68 -35
  3. package/README.md +65 -30
  4. package/dist/chunks/chunk-2C33MXSW.js +3 -0
  5. package/dist/chunks/chunk-34S5SQY6.js +2 -0
  6. package/dist/chunks/chunk-4WE3OO62.js +2 -0
  7. package/dist/chunks/chunk-5AYHCITP.js +2 -0
  8. package/dist/chunks/chunk-6JJQL6HL.js +2 -0
  9. package/dist/chunks/chunk-C7V2FH6L.js +3 -0
  10. package/dist/chunks/chunk-CZI7KUO3.js +2 -0
  11. package/dist/chunks/chunk-DXI5N2ET.js +2 -0
  12. package/dist/chunks/chunk-FY3FVOBM.js +2 -0
  13. package/dist/chunks/chunk-H3WVPZDL.js +2 -0
  14. package/dist/chunks/chunk-LHUIJQHY.js +2 -0
  15. package/dist/chunks/chunk-LV3W2F7N.js +2 -0
  16. package/dist/chunks/chunk-M4ITG7YR.js +2 -0
  17. package/dist/chunks/chunk-NSYZTS26.js +2 -0
  18. package/dist/chunks/chunk-ONY5CISH.js +2 -0
  19. package/dist/chunks/chunk-RFE7MVP7.js +2 -0
  20. package/dist/chunks/chunk-SE7V2KLO.js +2 -0
  21. package/dist/chunks/chunk-THIGHOKK.js +2 -0
  22. package/dist/chunks/chunk-TNMJPQPV.js +2 -0
  23. package/dist/chunks/chunk-WM7VFXTV.js +2 -0
  24. package/dist/chunks/chunk-WMDYDTVQ.js +2 -0
  25. package/dist/chunks/chunk-XLSFJTTK.js +2 -0
  26. package/dist/chunks/chunk-Z37NELOS.js +2 -0
  27. package/dist/chunks/chunk-ZFQWB222.js +2 -0
  28. package/dist/data/grouping.js +26 -7
  29. package/dist/descriptive/basic.js +110 -8
  30. package/dist/descriptive/cov.js +23 -4
  31. package/dist/descriptive/dataFrames.d.ts +4 -2
  32. package/dist/descriptive/dataFrames.js +69 -23
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +26 -9
  35. package/dist/descriptive/hist.d.ts +8 -5
  36. package/dist/descriptive/hist.js +77 -31
  37. package/dist/descriptive/missing.js +3 -1
  38. package/dist/descriptive/moments.js +86 -19
  39. package/dist/descriptive/omega.d.ts +1 -1
  40. package/dist/descriptive/omega.js +74 -10
  41. package/dist/descriptive/pivot.d.ts +25 -10
  42. package/dist/descriptive/pivot.js +182 -42
  43. package/dist/descriptive/quantile.js +10 -1
  44. package/dist/descriptive/rank.js +8 -1
  45. package/dist/descriptive/table.d.ts +23 -3
  46. package/dist/descriptive/table.js +36 -21
  47. package/dist/descriptive.js +2 -2
  48. package/dist/distributions/arcsine.js +27 -2
  49. package/dist/distributions/beta.js +33 -4
  50. package/dist/distributions/binomial.js +46 -14
  51. package/dist/distributions/bvnorm.js +11 -2
  52. package/dist/distributions/cauchy.js +21 -4
  53. package/dist/distributions/chisq.js +16 -3
  54. package/dist/distributions/exponential.js +14 -0
  55. package/dist/distributions/f.js +41 -17
  56. package/dist/distributions/gamma.js +35 -3
  57. package/dist/distributions/geometric.js +58 -13
  58. package/dist/distributions/hypergeometric.d.ts +5 -1
  59. package/dist/distributions/hypergeometric.js +101 -6
  60. package/dist/distributions/invgamma.js +10 -1
  61. package/dist/distributions/kumaraswamy.js +9 -0
  62. package/dist/distributions/laplace.js +36 -6
  63. package/dist/distributions/logistic.js +13 -1
  64. package/dist/distributions/lognormal.js +16 -2
  65. package/dist/distributions/multinomial.js +58 -11
  66. package/dist/distributions/nbeta.js +62 -11
  67. package/dist/distributions/nchisq.js +30 -6
  68. package/dist/distributions/negbinomial.js +102 -17
  69. package/dist/distributions/normal.js +17 -4
  70. package/dist/distributions/nt.js +392 -17
  71. package/dist/distributions/pareto.js +12 -1
  72. package/dist/distributions/poisson.js +37 -3
  73. package/dist/distributions/signrank.js +16 -4
  74. package/dist/distributions/summary.d.ts +2 -1
  75. package/dist/distributions/summary.js +481 -61
  76. package/dist/distributions/t.js +9 -0
  77. package/dist/distributions/triangular.js +19 -5
  78. package/dist/distributions/tukey.js +11 -2
  79. package/dist/distributions/uniform.js +8 -0
  80. package/dist/distributions/weibull.js +18 -0
  81. package/dist/distributions/wilcox.d.ts +9 -3
  82. package/dist/distributions/wilcox.js +164 -26
  83. package/dist/distributions.js +2 -2
  84. package/dist/entries/descriptive.d.ts +3 -1
  85. package/dist/entries/descriptive.js +1 -1
  86. package/dist/entries/distributions.d.ts +1 -0
  87. package/dist/entries/distributions.js +2 -0
  88. package/dist/entries/linalg.d.ts +3 -1
  89. package/dist/entries/mixed.d.ts +3 -0
  90. package/dist/entries/mixed.js +2 -0
  91. package/dist/entries/numerics.d.ts +2 -1
  92. package/dist/entries/tests.d.ts +8 -5
  93. package/dist/entries/tests.js +3 -1
  94. package/dist/htest/agreement.d.ts +16 -2
  95. package/dist/htest/agreement.js +122 -21
  96. package/dist/htest/ansariTest.d.ts +8 -2
  97. package/dist/htest/ansariTest.js +116 -18
  98. package/dist/htest/aov.d.ts +29 -23
  99. package/dist/htest/aov.js +90 -47
  100. package/dist/htest/binomTest.d.ts +5 -0
  101. package/dist/htest/binomTest.js +47 -17
  102. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  103. package/dist/htest/brunnerMunzelTest.js +12 -5
  104. package/dist/htest/chisqTest.d.ts +5 -2
  105. package/dist/htest/chisqTest.js +151 -46
  106. package/dist/htest/cor.d.ts +9 -2
  107. package/dist/htest/cor.js +57 -26
  108. package/dist/htest/core/ansari.d.ts +9 -0
  109. package/dist/htest/core/ansari.js +21 -1
  110. package/dist/htest/core/kolmogorov.d.ts +25 -0
  111. package/dist/htest/core/kolmogorov.js +123 -0
  112. package/dist/htest/core/mantelhaen.js +6 -4
  113. package/dist/htest/core/shapiro.d.ts +1 -1
  114. package/dist/htest/core/shapiro.js +5 -1
  115. package/dist/htest/core/simulate.d.ts +6 -0
  116. package/dist/htest/core/simulate.js +20 -0
  117. package/dist/htest/dunnett.js +14 -5
  118. package/dist/htest/effectSize.d.ts +5 -0
  119. package/dist/htest/effectSize.js +117 -35
  120. package/dist/htest/fisherTest.d.ts +4 -3
  121. package/dist/htest/fisherTest.js +88 -24
  122. package/dist/htest/groups.d.ts +7 -0
  123. package/dist/htest/groups.js +21 -4
  124. package/dist/htest/ksTest.d.ts +7 -1
  125. package/dist/htest/ksTest.js +36 -6
  126. package/dist/htest/leveneTest.d.ts +2 -0
  127. package/dist/htest/leveneTest.js +28 -6
  128. package/dist/htest/mantelhaenTest.js +132 -25
  129. package/dist/htest/mcnemarTest.js +40 -11
  130. package/dist/htest/multipleComparisons.d.ts +24 -26
  131. package/dist/htest/multipleComparisons.js +70 -64
  132. package/dist/htest/normalityTests.js +54 -14
  133. package/dist/htest/onewayTest.js +106 -5
  134. package/dist/htest/pAdjust.d.ts +3 -2
  135. package/dist/htest/pAdjust.js +42 -6
  136. package/dist/htest/pairwise.d.ts +3 -1
  137. package/dist/htest/pairwise.js +46 -21
  138. package/dist/htest/poissonTest.d.ts +1 -1
  139. package/dist/htest/poissonTest.js +117 -59
  140. package/dist/htest/polycor.js +47 -17
  141. package/dist/htest/power.d.ts +15 -1
  142. package/dist/htest/power.js +128 -10
  143. package/dist/htest/propTest.d.ts +3 -0
  144. package/dist/htest/propTest.js +44 -6
  145. package/dist/htest/pwr.d.ts +38 -1
  146. package/dist/htest/pwr.js +159 -39
  147. package/dist/htest/rankTests.js +36 -6
  148. package/dist/htest/tTest.d.ts +2 -0
  149. package/dist/htest/tTest.js +53 -21
  150. package/dist/htest/testFormula.js +11 -11
  151. package/dist/htest/trendTests.d.ts +28 -4
  152. package/dist/htest/trendTests.js +124 -35
  153. package/dist/htest/types.d.ts +7 -0
  154. package/dist/htest/types.js +7 -0
  155. package/dist/htest/varTest.js +52 -14
  156. package/dist/htest/wilcoxTest.js +164 -29
  157. package/dist/integrate/quadpack.js +27 -5
  158. package/dist/internal/checkOptions.d.ts +11 -0
  159. package/dist/internal/checkOptions.js +31 -0
  160. package/dist/internal/covmat.d.ts +5 -0
  161. package/dist/internal/covmat.js +20 -0
  162. package/dist/internal/ddexp.d.ts +15 -1
  163. package/dist/internal/ddexp.js +59 -6
  164. package/dist/internal/discrete.d.ts +14 -0
  165. package/dist/internal/discrete.js +78 -5
  166. package/dist/internal/extremes.d.ts +9 -0
  167. package/dist/internal/extremes.js +24 -0
  168. package/dist/internal/fround.js +13 -4
  169. package/dist/internal/integer.d.ts +9 -0
  170. package/dist/internal/integer.js +12 -0
  171. package/dist/internal/invert.js +15 -2
  172. package/dist/internal/optionalArgs.d.ts +12 -0
  173. package/dist/internal/optionalArgs.js +46 -0
  174. package/dist/internal/scaledInverse.d.ts +10 -0
  175. package/dist/internal/scaledInverse.js +22 -0
  176. package/dist/internal/seq.js +15 -2
  177. package/dist/internal/summary.d.ts +90 -0
  178. package/dist/internal/summary.js +458 -39
  179. package/dist/internal/uniroot.d.ts +7 -0
  180. package/dist/internal/uniroot.js +28 -3
  181. package/dist/internal/warnings.d.ts +66 -0
  182. package/dist/internal/warnings.js +122 -0
  183. package/dist/linalg/basic.d.ts +3 -1
  184. package/dist/linalg/basic.js +58 -7
  185. package/dist/linalg/chol.js +10 -1
  186. package/dist/linalg/dot.d.ts +29 -0
  187. package/dist/linalg/dot.js +132 -0
  188. package/dist/linalg/eigen.d.ts +6 -1
  189. package/dist/linalg/eigen.js +75 -14
  190. package/dist/linalg/expm.d.ts +3 -2
  191. package/dist/linalg/expm.js +113 -15
  192. package/dist/linalg/kappa.js +64 -10
  193. package/dist/linalg/lu.d.ts +2 -1
  194. package/dist/linalg/lu.js +40 -5
  195. package/dist/linalg/matrix.d.ts +14 -0
  196. package/dist/linalg/matrix.js +24 -0
  197. package/dist/linalg/norm.js +4 -0
  198. package/dist/linalg/ops.d.ts +27 -2
  199. package/dist/linalg/ops.js +74 -26
  200. package/dist/linalg/qr.d.ts +2 -1
  201. package/dist/linalg/qr.js +105 -23
  202. package/dist/linalg/schur.js +11 -3
  203. package/dist/linalg/solve.d.ts +6 -1
  204. package/dist/linalg/solve.js +156 -26
  205. package/dist/linalg/svd.d.ts +9 -2
  206. package/dist/linalg/svd.js +33 -11
  207. package/dist/linalg.js +2 -2
  208. package/dist/mixed.js +4 -4
  209. package/dist/models/anovaSequential.d.ts +32 -2
  210. package/dist/models/anovaSequential.js +170 -28
  211. package/dist/models/aovEz.js +154 -39
  212. package/dist/models/aovStrata.js +68 -24
  213. package/dist/models/carAnova.d.ts +1 -1
  214. package/dist/models/carAnova.js +78 -33
  215. package/dist/models/coxph.d.ts +6 -0
  216. package/dist/models/coxph.js +166 -69
  217. package/dist/models/estimable.d.ts +15 -0
  218. package/dist/models/estimable.js +68 -0
  219. package/dist/models/formula.d.ts +1 -1
  220. package/dist/models/formula.js +26 -8
  221. package/dist/models/glm.d.ts +57 -7
  222. package/dist/models/glm.js +427 -74
  223. package/dist/models/glmAnova.js +90 -14
  224. package/dist/models/glmConfint.d.ts +1 -1
  225. package/dist/models/glmConfint.js +121 -29
  226. package/dist/models/glmFamily.d.ts +11 -6
  227. package/dist/models/glmFamily.js +247 -62
  228. package/dist/models/lm.d.ts +12 -1
  229. package/dist/models/lm.js +246 -37
  230. package/dist/models/lmer.d.ts +31 -7
  231. package/dist/models/lmer.js +129 -42
  232. package/dist/models/lmerAnova.d.ts +3 -3
  233. package/dist/models/lmerAnova.js +47 -9
  234. package/dist/models/lmerHypotheses.d.ts +6 -2
  235. package/dist/models/lmerHypotheses.js +14 -2
  236. package/dist/models/lmerTest.d.ts +13 -6
  237. package/dist/models/lmerTest.js +82 -29
  238. package/dist/models/mauchly.d.ts +6 -1
  239. package/dist/models/mauchly.js +41 -15
  240. package/dist/models/mixedStructure.js +6 -0
  241. package/dist/models/modelFrame.js +10 -4
  242. package/dist/models/modelMatrix.d.ts +3 -1
  243. package/dist/models/modelMatrix.js +47 -17
  244. package/dist/models/scaledTables.d.ts +8 -0
  245. package/dist/models/scaledTables.js +6 -0
  246. package/dist/models/survival.d.ts +12 -1
  247. package/dist/models/survival.js +75 -28
  248. package/dist/models/tiedTimes.d.ts +2 -0
  249. package/dist/models/tiedTimes.js +34 -0
  250. package/dist/numerics/deriv.d.ts +1 -1
  251. package/dist/numerics/deriv.js +72 -8
  252. package/dist/numerics/integrate.d.ts +9 -1
  253. package/dist/numerics/integrate.js +111 -16
  254. package/dist/numerics/interp.d.ts +40 -9
  255. package/dist/numerics/interp.js +375 -55
  256. package/dist/numerics/ode.js +59 -1
  257. package/dist/numerics.js +2 -2
  258. package/dist/optim/localmin.js +4 -0
  259. package/dist/optim/optim.d.ts +3 -1
  260. package/dist/optim/optim.js +97 -10
  261. package/dist/random/beta.js +58 -4
  262. package/dist/random/binomial.d.ts +14 -3
  263. package/dist/random/binomial.js +59 -24
  264. package/dist/random/continuous.js +50 -5
  265. package/dist/random/extra.js +55 -9
  266. package/dist/random/gamma.d.ts +4 -1
  267. package/dist/random/gamma.js +47 -8
  268. package/dist/random/hyper.js +9 -6
  269. package/dist/random/mt.js +17 -2
  270. package/dist/random/poisson.js +31 -3
  271. package/dist/random/r2dtable.d.ts +8 -1
  272. package/dist/random/r2dtable.js +24 -3
  273. package/dist/random/rank.d.ts +2 -0
  274. package/dist/random/rank.js +44 -4
  275. package/dist/random/rng.js +4 -0
  276. package/dist/random/sample.d.ts +12 -2
  277. package/dist/random/sample.js +63 -20
  278. package/dist/random/streams.js +4 -2
  279. package/dist/rstats.js +17 -14
  280. package/dist/special/besselIK.d.ts +12 -0
  281. package/dist/special/besselIK.js +175 -23
  282. package/dist/special/besselJY.d.ts +11 -1
  283. package/dist/special/besselJY.js +127 -19
  284. package/dist/special/besselSeries.d.ts +27 -0
  285. package/dist/special/besselSeries.js +45 -2
  286. package/dist/special/beta.js +4 -1
  287. package/dist/special/choose.js +24 -8
  288. package/dist/special/dd.js +122 -18
  289. package/dist/special/extra.js +14 -2
  290. package/dist/special/gamma.js +11 -2
  291. package/dist/special/incbet.js +30 -4
  292. package/dist/special/incbetTemme.d.ts +7 -0
  293. package/dist/special/incbetTemme.js +45 -12
  294. package/dist/special/loader.d.ts +1 -1
  295. package/dist/special/loader.js +117 -20
  296. package/dist/special/log1pmx.js +4 -0
  297. package/dist/special/psigamma.js +7 -0
  298. package/dist/special.js +2 -2
  299. package/dist/tests.js +15 -11
  300. package/llms.txt +15 -6
  301. package/package.json +19 -10
  302. package/dist/chunks/chunk-3THFTB36.js +0 -2
  303. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  304. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  305. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  306. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  307. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  308. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  309. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  310. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  311. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  312. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  313. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  314. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  315. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  316. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  317. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  318. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  319. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  320. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  321. package/dist/chunks/chunk-VLUL2HFW.js +0 -3
  322. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
@@ -7,6 +7,7 @@
7
7
  import { unifRand } from "./rng.js";
8
8
  import { generate, powInt } from "./common.js";
9
9
  import { qbinom } from "../distributions/binomial.js";
10
+ import { maxOf } from "../internal/extremes.js";
10
11
  const INT_MAX = 2147483647;
11
12
  // Values rebuilt only when the parameters change
12
13
  let c = 0, fm = 0, npq = 0, p1 = 0, p2 = 0, p3 = 0, p4 = 0, qn = 0;
@@ -17,6 +18,25 @@ function stirlingTail(z) {
17
18
  const z2 = z * z;
18
19
  return (13860 - (462 - (132 - (99 - 140 / z2) / z2) / z2) / z2) / z / 166320;
19
20
  }
21
+ /**
22
+ * log(f(ix) / f(m)) for the binomial probabilities f with n trials and success probability p = 1 - q, m the integer
23
+ * mode, by Stirling's formula (the final test of BTPE). The corrections of log m! and log (n - m)! enter with a plus
24
+ * sign and those of log ix! and log (n - ix)! with a minus sign; R's rbinom.c adds all four (an error of up to about
25
+ * 0.02 in the log near n p = 30), which changes some acceptances and so the stream from R's
26
+ */
27
+ export function btpeLogRatio(n, p, q, m, ix) {
28
+ const x1 = ix + 1;
29
+ const f1 = m + 1;
30
+ const z = n + 1 - m;
31
+ const w = n - ix + 1;
32
+ return ((m + 0.5) * Math.log(f1 / x1) +
33
+ (n - m + 0.5) * Math.log(z / w) +
34
+ (ix - m) * Math.log((w * p) / (x1 * q)) +
35
+ stirlingTail(f1) +
36
+ stirlingTail(z) -
37
+ stirlingTail(x1) -
38
+ stirlingTail(w));
39
+ }
20
40
  /** One binomial variate (nin trials, success probability pp) */
21
41
  export function rbinom1(nin, pp) {
22
42
  if (!Number.isFinite(nin))
@@ -43,7 +63,8 @@ export function rbinom1(nin, pp) {
43
63
  psave = pp;
44
64
  nsave = n;
45
65
  if (np < 30) {
46
- qn = powInt(q, n);
66
+ // (q = 1 - p rounds to 1 below p = 1.1e-16, and q^n to 1: every draw was 0, as in R 4.5.2; issue #31)
67
+ qn = q === 1 && p > 0 ? Math.exp(n * Math.log1p(-p)) : powInt(q, n);
47
68
  small = true;
48
69
  }
49
70
  else {
@@ -141,21 +162,9 @@ export function rbinom1(nin, pp) {
141
162
  if (alv < ynorm - amaxp)
142
163
  break;
143
164
  if (alv <= ynorm + amaxp) {
144
- // Final test using Stirling's formula (M is the integer mode m)
145
- const x1 = ix + 1;
146
- const f1 = m + 1;
147
- const z = n + 1 - m;
148
- const w = n - ix + 1;
149
- if (alv <=
150
- xm * Math.log(f1 / x1) +
151
- (n - m + 0.5) * Math.log(z / w) +
152
- (ix - m) * Math.log((w * p) / (x1 * q)) +
153
- stirlingTail(f1) +
154
- stirlingTail(z) +
155
- stirlingTail(x1) +
156
- stirlingTail(w)) {
165
+ // Final test using Stirling's formula
166
+ if (alv <= btpeLogRatio(n, p, q, m, ix))
157
167
  break;
158
- }
159
168
  }
160
169
  }
161
170
  }
@@ -167,6 +176,10 @@ export function rbinom1(nin, pp) {
167
176
  /**
168
177
  * Random numbers from the binomial distribution. Equivalent to R's `rbinom()`.
169
178
  *
179
+ * For `size * min(prob, 1 - prob) >= 30` (algorithm BTPE) the stream can depart from R's: R's final acceptance test has
180
+ * two Stirling corrections with the wrong sign, and here the signs are right (`setSeed(439); rbinom(1, 10000, 0.5)` is
181
+ * 4879, R 5023). Below 30 (inversion) the stream is R's.
182
+ *
170
183
  * @param n Number of values to generate (fractions are truncated, as in R).
171
184
  * @param size Number of trials.
172
185
  * @param prob Probability of success in each trial.
@@ -190,10 +203,10 @@ export function rbinom(n, size, prob) {
190
203
  * with one draw per row (the transpose of R's result). The random stream is the same as R's.
191
204
  *
192
205
  * @param n Number of values to generate (fractions are truncated, as in R).
193
- * @param size Number of objects distributed into the K categories in each draw.
206
+ * @param size Number of objects distributed into the K categories in each draw (fractions are truncated, as in R).
194
207
  * @param prob Category weights of length K. They need not sum to 1 (they are divided by their sum).
195
- * @returns An array of `n` arrays, each of length K and summing to `size`.
196
- * @throws RangeError if `size` is not a non-negative integer, or `prob` has a negative or
208
+ * @returns An array of `n` arrays, each of length K and summing to the truncated `size`.
209
+ * @throws RangeError if the truncated `size` is negative or 2^31 or more, or `prob` has a negative or
197
210
  * non-finite value, or no positive value.
198
211
  *
199
212
  * @example
@@ -205,8 +218,11 @@ export function rbinom(n, size, prob) {
205
218
  * @category Random numbers
206
219
  */
207
220
  export function rmultinom(n, size, prob) {
208
- if (!Number.isFinite(size) || size < 0 || Math.round(size) !== size)
209
- throw new RangeError("size must be a non-negative integer");
221
+ // as R, whose size is an integer: up to 2^31 - 1, truncated first (a size in (-1, 0) is 0; #412)
222
+ if (!Number.isFinite(size) || size <= -1 || size >= 2147483648) {
223
+ throw new RangeError("size must be non-negative, truncated to an integer up to 2147483647");
224
+ }
225
+ const total = Math.max(0, Math.trunc(size));
210
226
  let sum = 0;
211
227
  for (const v of prob) {
212
228
  if (!Number.isFinite(v) || v < 0)
@@ -215,15 +231,33 @@ export function rmultinom(n, size, prob) {
215
231
  }
216
232
  if (sum === 0)
217
233
  throw new RangeError("prob must contain at least one positive value");
218
- const pr = prob.map((v) => v / sum);
234
+ let pr;
235
+ if (sum === Infinity) {
236
+ // Finite weights whose sum overflows: rescale by the largest before summing
237
+ const mx = maxOf(prob);
238
+ sum = 0;
239
+ for (const v of prob)
240
+ sum += v / mx;
241
+ pr = prob.map((v) => v / mx / sum);
242
+ }
243
+ else {
244
+ pr = prob.map((v) => v / sum);
245
+ }
219
246
  const K = pr.length;
247
+ // the probabilities from k on, summed from the end: pTot below (1 less the earlier ones, as R) can reach pr[k] while
248
+ // later categories still have probability (c(0.5, 0.5, 1e-16) sums to 1 in doubles, and the third was always 0)
249
+ const rest = new Array(K + 1).fill(0);
250
+ for (let k = K - 1; k >= 0; k--)
251
+ rest[k] = rest[k + 1] + pr[k];
220
252
  const draw = () => {
221
253
  const out = new Array(K).fill(0);
222
- let left = size;
254
+ let left = total;
223
255
  let pTot = 1;
224
256
  for (let k = 0; k < K - 1; k++) {
225
257
  if (pr[k]) {
226
- const pk = pr[k] / pTot;
258
+ let pk = pr[k] / pTot;
259
+ if (pk >= 1 && rest[k + 1] > 0)
260
+ pk = pr[k] / rest[k];
227
261
  out[k] = pk < 1 ? rbinom1(left, pk) : left;
228
262
  left -= out[k];
229
263
  }
@@ -234,7 +268,8 @@ export function rmultinom(n, size, prob) {
234
268
  out[K - 1] = left;
235
269
  return out;
236
270
  };
237
- if (!Number.isFinite(n) || n < 0)
271
+ // truncated first, as R: an n in (-1, 0) is 0 (#412)
272
+ if (!Number.isFinite(n) || n <= -1)
238
273
  throw new RangeError("n must be a non-negative finite number");
239
274
  return Array.from({ length: Math.trunc(n) }, draw);
240
275
  }
@@ -4,6 +4,18 @@
4
4
  // (verified by next in test/fixtures/random*.json).
5
5
  import { expRand, normRand, unifRand } from "./rng.js";
6
6
  import { generate } from "./common.js";
7
+ import { ddExp } from "../internal/ddexp.js";
8
+ import { ddAdd, ddLog, ddMulNum } from "../special/dd.js";
9
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
10
+ import { checkOptions } from "../internal/checkOptions.js";
11
+ const RUNIF_KEYS = ["min", "max"];
12
+ const RNORM_KEYS = ["mean", "sd"];
13
+ const REXP_KEYS = ["rate"];
14
+ const RLNORM_KEYS = ["meanlog", "sdlog"];
15
+ const RLOGIS_KEYS = ["location", "scale"];
16
+ const RCAUCHY_KEYS = ["location", "scale"];
17
+ const RWEIBULL_KEYS = ["scale"];
18
+ // Generated by `node scripts/option-keys.mjs --write` (end)
7
19
  /**
8
20
  * Random numbers from the uniform distribution. Equivalent to R's `runif()`.
9
21
  *
@@ -22,6 +34,7 @@ import { generate } from "./common.js";
22
34
  * @category Random numbers
23
35
  */
24
36
  export function runif(n, options = {}) {
37
+ checkOptions(options, RUNIF_KEYS, "runif"); // generated: option-keys.mjs
25
38
  const { min = 0, max = 1 } = options;
26
39
  return generate(n, () => {
27
40
  if (!Number.isFinite(min) || !Number.isFinite(max) || max < min)
@@ -29,7 +42,8 @@ export function runif(n, options = {}) {
29
42
  if (min === max)
30
43
  return min;
31
44
  const u = unifRand();
32
- return min + (max - min) * u;
45
+ // a width that overflows (R returns Inf): the weighted mean of the ends instead
46
+ return Number.isFinite(max - min) ? min + (max - min) * u : min * (1 - u) + max * u;
33
47
  });
34
48
  }
35
49
  export function rnorm1(mean, sd) {
@@ -37,7 +51,11 @@ export function rnorm1(mean, sd) {
37
51
  return NaN;
38
52
  if (sd === 0 || !Number.isFinite(mean))
39
53
  return mean;
40
- return mean + sd * normRand();
54
+ const z = normRand();
55
+ const x = mean + sd * z;
56
+ // sd·Z can overflow although mean + sd·Z is in range (R gives ±Inf): the same sum halved (exact for such a large sd
57
+ // and a mean that matters), rounded once and doubled
58
+ return Number.isFinite(x) ? x : 2 * (mean / 2 + (sd / 2) * z);
41
59
  }
42
60
  /**
43
61
  * Random numbers from the normal distribution. Equivalent to R's `rnorm()`.
@@ -59,6 +77,7 @@ export function rnorm1(mean, sd) {
59
77
  * @category Random numbers
60
78
  */
61
79
  export function rnorm(n, options = {}) {
80
+ checkOptions(options, RNORM_KEYS, "rnorm"); // generated: option-keys.mjs
62
81
  const { mean = 0, sd = 1 } = options;
63
82
  return generate(n, () => rnorm1(mean, sd));
64
83
  }
@@ -78,8 +97,14 @@ export function rnorm(n, options = {}) {
78
97
  * @category Random numbers
79
98
  */
80
99
  export function rexp(n, options = {}) {
81
- const scale = 1 / (options.rate ?? 1);
100
+ checkOptions(options, REXP_KEYS, "rexp"); // generated: option-keys.mjs
101
+ const rate = options.rate ?? 1;
102
+ const scale = 1 / rate;
82
103
  return generate(n, () => {
104
+ // a positive rate below about 5.6e-309 has 1 / rate = Infinity: the variate itself (R gives NaN), which overflows
105
+ // unless the exponential variate is small
106
+ if (scale === Infinity && rate > 0)
107
+ return expRand() / rate;
83
108
  if (!Number.isFinite(scale) || scale <= 0)
84
109
  return scale === 0 ? 0 : NaN;
85
110
  return scale * expRand();
@@ -102,6 +127,7 @@ export function rexp(n, options = {}) {
102
127
  * @category Random numbers
103
128
  */
104
129
  export function rlnorm(n, options = {}) {
130
+ checkOptions(options, RLNORM_KEYS, "rlnorm"); // generated: option-keys.mjs
105
131
  const { meanlog = 0, sdlog = 1 } = options;
106
132
  return generate(n, () => {
107
133
  if (Number.isNaN(meanlog) || !Number.isFinite(sdlog) || sdlog < 0)
@@ -126,10 +152,17 @@ export function rlnorm(n, options = {}) {
126
152
  * @category Random numbers
127
153
  */
128
154
  export function rlogis(n, options = {}) {
155
+ checkOptions(options, RLOGIS_KEYS, "rlogis"); // generated: option-keys.mjs
129
156
  const { location = 0, scale = 1 } = options;
130
157
  return generate(n, () => {
131
158
  if (Number.isNaN(location) || !Number.isFinite(scale))
132
159
  return NaN;
160
+ // a negative scale defines no distribution (dlogis, plogis and qlogis give NaN; R draws from it). The uniform R
161
+ // draws is drawn as well, so the stream stays R's
162
+ if (scale < 0) {
163
+ unifRand();
164
+ return NaN;
165
+ }
133
166
  if (scale === 0 || !Number.isFinite(location))
134
167
  return location;
135
168
  const u = unifRand();
@@ -153,6 +186,7 @@ export function rlogis(n, options = {}) {
153
186
  * @category Random numbers
154
187
  */
155
188
  export function rcauchy(n, options = {}) {
189
+ checkOptions(options, RCAUCHY_KEYS, "rcauchy"); // generated: option-keys.mjs
156
190
  const { location = 0, scale = 1 } = options;
157
191
  return generate(n, () => {
158
192
  if (Number.isNaN(location) || !Number.isFinite(scale) || scale < 0)
@@ -179,11 +213,22 @@ export function rcauchy(n, options = {}) {
179
213
  * @category Random numbers
180
214
  */
181
215
  export function rweibull(n, shape, options = {}) {
216
+ checkOptions(options, RWEIBULL_KEYS, "rweibull"); // generated: option-keys.mjs
182
217
  const { scale = 1 } = options;
183
218
  return generate(n, () => {
184
- if (!Number.isFinite(shape) || !Number.isFinite(scale) || shape <= 0 || scale <= 0) {
219
+ // an invalid shape (or a negative scale) is NaN also with scale = 0 (R returns 0 there; no variate is drawn either
220
+ // way); scale = 0 is the point mass at 0
221
+ if (!(shape > 0) || !(scale >= 0))
222
+ return NaN;
223
+ if (!Number.isFinite(shape) || !Number.isFinite(scale) || scale === 0) {
185
224
  return scale === 0 ? 0 : NaN;
186
225
  }
187
- return scale * Math.pow(-Math.log(unifRand()), 1 / shape);
226
+ const e = -Math.log(unifRand());
227
+ const p = Math.pow(e, 1 / shape);
228
+ // for a small shape the power can overflow although the variate is in range for a small scale (R gives Inf): in
229
+ // logs then, double-double so that the large log keeps its digits
230
+ if (p !== Infinity)
231
+ return scale * p;
232
+ return ddExp(ddAdd(ddLog([scale, 0]), ddMulNum(ddLog([e, 0]), 1 / shape)))[0];
188
233
  });
189
234
  }
@@ -11,6 +11,15 @@ import { qpareto1 } from "../distributions/pareto.js";
11
11
  import { generate } from "./common.js";
12
12
  import { rgamma1 } from "./gamma.js";
13
13
  import { expRand, unifRand } from "./rng.js";
14
+ import { midpoint } from "../internal/extremes.js";
15
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
16
+ import { checkOptions } from "../internal/checkOptions.js";
17
+ const RINVGAMMA_KEYS = ["beta"];
18
+ const RPARETO_KEYS = ["a", "b"];
19
+ const RTRIANG_KEYS = ["a", "b", "c"];
20
+ const RLAPLACE_KEYS = ["mu", "sigma"];
21
+ const RARCSINE_KEYS = ["a", "b"];
22
+ // Generated by `node scripts/option-keys.mjs --write` (end)
14
23
  /**
15
24
  * Random numbers from the inverse gamma distribution. Equivalent to `extraDistr::rinvgamma(n, alpha, beta = 1)` in R.
16
25
  *
@@ -27,8 +36,15 @@ import { expRand, unifRand } from "./rng.js";
27
36
  * @category Random numbers
28
37
  */
29
38
  export function rinvgamma(n, alpha, options = {}) {
39
+ checkOptions(options, RINVGAMMA_KEYS, "rinvgamma"); // generated: option-keys.mjs
30
40
  const { beta = 1 } = options;
31
- return generate(n, () => (alpha > 0 && beta > 0 && Number.isFinite(alpha) && Number.isFinite(beta) ? 1 / rgamma1(alpha, 1 / beta) : NaN));
41
+ // alpha = Inf is the limit 0, as qinvgamma (extraDistr's 1/rgamma: no uniform drawn); beta = Inf is NaN, as the
42
+ // density, distribution and quantile functions, also without a draw (extraDistr: Inf; issue #92)
43
+ return generate(n, () => {
44
+ if (!(alpha > 0 && beta > 0) || beta === Infinity)
45
+ return NaN;
46
+ return alpha === Infinity ? 0 : 1 / rgamma1(alpha, 1 / beta);
47
+ });
32
48
  }
33
49
  /**
34
50
  * Random numbers from the Kumaraswamy distribution. Equivalent to `extraDistr::rkumar(n, a, b)` in R.
@@ -42,7 +58,14 @@ export function rinvgamma(n, alpha, options = {}) {
42
58
  * @category Random numbers
43
59
  */
44
60
  export function rkumar(n, a, b) {
45
- return generate(n, () => (a > 0 && b > 0 && Number.isFinite(a) && Number.isFinite(b) ? qkumar1(1 - unifRand(), a, b, true, false) : NaN));
61
+ // a = Inf is the limit 1, as qkumar; b = Inf is NaN, as dkumar, pkumar and qkumar, after the uniform extraDistr draws
62
+ // (it gives 0; issue #92)
63
+ return generate(n, () => {
64
+ if (!(a > 0 && b > 0))
65
+ return NaN;
66
+ const u = unifRand();
67
+ return b === Infinity ? NaN : qkumar1(1 - u, a, b, true, false);
68
+ });
46
69
  }
47
70
  /**
48
71
  * Random numbers from the Pareto distribution. Equivalent to `extraDistr::rpareto(n, a = 1, b = 1)` in R.
@@ -56,8 +79,16 @@ export function rkumar(n, a, b) {
56
79
  * @category Random numbers
57
80
  */
58
81
  export function rpareto(n, options = {}) {
82
+ checkOptions(options, RPARETO_KEYS, "rpareto"); // generated: option-keys.mjs
59
83
  const { a = 1, b = 1 } = options;
60
- return generate(n, () => (a > 0 && b > 0 && Number.isFinite(a) && Number.isFinite(b) ? qpareto1(1 - unifRand(), a, b, true, false) : NaN));
84
+ // a = Inf is the limit b, as qpareto; b = Inf is NaN, as dpareto, ppareto and qpareto, after the uniform extraDistr
85
+ // draws (it gives Inf; issue #92)
86
+ return generate(n, () => {
87
+ if (!(a > 0 && b > 0))
88
+ return NaN;
89
+ const u = unifRand();
90
+ return b === Infinity ? NaN : qpareto1(1 - u, a, b, true, false);
91
+ });
61
92
  }
62
93
  /**
63
94
  * Random numbers from the triangular distribution.
@@ -72,15 +103,25 @@ export function rpareto(n, options = {}) {
72
103
  * @category Random numbers
73
104
  */
74
105
  export function rtriang(n, options = {}) {
106
+ checkOptions(options, RTRIANG_KEYS, "rtriang"); // generated: option-keys.mjs
75
107
  const { a = -1, b = 1 } = options;
76
- const c = options.c ?? (a + b) / 2;
108
+ const c = options.c ?? midpoint(a, b);
77
109
  return generate(n, () => {
78
- if (!(Number.isFinite(a) && Number.isFinite(b) && a < b && a <= c && c <= b))
110
+ if (!(a < b && a <= c && c <= b))
79
111
  return NaN;
80
112
  const u = unifRand();
81
113
  const v = unifRand();
82
- const cc = (c - a) / (b - a);
83
- return a + (b - a) * ((1 - cc) * Math.min(u, v) + cc * Math.max(u, v));
114
+ // an infinite endpoint is NaN, as dtriang, ptriang and qtriang, after the two uniforms extraDistr draws (it gives
115
+ // Inf for b = Inf with a finite c, NaN otherwise; issue #428)
116
+ if (!(Number.isFinite(a) && Number.isFinite(b)))
117
+ return NaN;
118
+ // b - a overflows for a range wider than the largest double: then from the halves of a, b and c (exact), the
119
+ // result doubled back (it lies in [a, b], so it is finite)
120
+ const wide = !Number.isFinite(b - a);
121
+ const [ah, bh, ch] = wide ? [a / 2, b / 2, c / 2] : [a, b, c];
122
+ const cc = (ch - ah) / (bh - ah);
123
+ const t = ah + (bh - ah) * ((1 - cc) * Math.min(u, v) + cc * Math.max(u, v));
124
+ return wide ? t * 2 : t;
84
125
  });
85
126
  }
86
127
  /**
@@ -95,13 +136,17 @@ export function rtriang(n, options = {}) {
95
136
  * @category Random numbers
96
137
  */
97
138
  export function rlaplace(n, options = {}) {
139
+ checkOptions(options, RLAPLACE_KEYS, "rlaplace"); // generated: option-keys.mjs
98
140
  const { mu = 0, sigma = 1 } = options;
141
+ // an infinite mu is the limit mu, as qlaplace; sigma = Inf with a finite mu is -Inf or Inf by the sign, the limit of
142
+ // qlaplace, as extraDistr (review 24 revision); both infinite is NaN, as qlaplace, after the draws extraDistr makes
143
+ // (issue #425)
99
144
  return generate(n, () => {
100
- if (!(Number.isFinite(mu) && sigma > 0 && Number.isFinite(sigma)))
145
+ if (Number.isNaN(mu) || !(sigma > 0))
101
146
  return NaN;
102
147
  const e = expRand();
103
148
  const s = unifRand() > 0.5 ? 1 : -1;
104
- return mu + sigma * s * e;
149
+ return sigma === Infinity && !Number.isFinite(mu) ? NaN : mu + sigma * s * e;
105
150
  });
106
151
  }
107
152
  /**
@@ -117,6 +162,7 @@ export function rlaplace(n, options = {}) {
117
162
  * @category Random numbers
118
163
  */
119
164
  export function rarcsine(n, options = {}) {
165
+ checkOptions(options, RARCSINE_KEYS, "rarcsine"); // generated: option-keys.mjs
120
166
  const { a = 0, b = 1 } = options;
121
167
  return generate(n, () => (Number.isFinite(a) && Number.isFinite(b) && a < b ? qarcsine1(unifRand(), a, b, true, false) : NaN));
122
168
  }
@@ -22,7 +22,10 @@ export declare function rgamma(n: number, shape: number, options?: {
22
22
  scale?: number;
23
23
  }): number[];
24
24
  export declare function rchisq1(df: number): number;
25
- /** One noncentral χ² variate: Poisson mixture (χ² with df + 2 × Poisson(ncp/2) degrees of freedom) */
25
+ /**
26
+ * One noncentral χ² variate: Poisson mixture (χ² with df + 2 × Poisson(ncp/2) degrees of freedom). df = Inf gives Inf
27
+ * after the Poisson (and χ²) variates, as R's rnchisq (which rejects only a NaN df); the central rchisq1 gives NaN there
28
+ */
26
29
  export declare function rnchisq1(df: number, ncp: number): number;
27
30
  /**
28
31
  * Random numbers from the chi-squared distribution. Equivalent to R's `rchisq()`.
@@ -10,6 +10,15 @@ import { gammaScale } from "../distributions/gamma.js";
10
10
  import { generate } from "./common.js";
11
11
  import { rpois1 } from "./poisson.js";
12
12
  import { rnorm1 } from "./continuous.js";
13
+ import { ddExp } from "../internal/ddexp.js";
14
+ import { ddAdd, ddDivNum, ddLog } from "../special/dd.js";
15
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
16
+ import { checkOptions } from "../internal/checkOptions.js";
17
+ const RGAMMA_KEYS = ["rate", "scale"];
18
+ const RCHISQ_KEYS = ["ncp"];
19
+ const RT_KEYS = ["ncp"];
20
+ const RF_KEYS = ["ncp"];
21
+ // Generated by `node scripts/option-keys.mjs --write` (end)
13
22
  const SQRT32 = 5.656854;
14
23
  const EXP_M1 = 0.36787944117144233; // exp(-1)
15
24
  // q_k and a_k of algorithm GD (tables in the paper)
@@ -33,16 +42,21 @@ function qOf(t) {
33
42
  export function rgamma1(a, scale) {
34
43
  if (Number.isNaN(a) || Number.isNaN(scale))
35
44
  return NaN;
36
- if (a <= 0 || scale <= 0)
37
- return scale === 0 || a === 0 ? 0 : NaN;
45
+ // a negative shape or scale defines no distribution, also when the other is 0 (R returns 0 there; no variate is
46
+ // drawn either way, so the stream is R's); shape 0 or scale 0 is the point mass at 0
47
+ if (a < 0 || scale < 0)
48
+ return NaN;
49
+ if (a === 0 || scale === 0)
50
+ return 0;
38
51
  if (!Number.isFinite(a) || !Number.isFinite(scale))
39
52
  return Infinity;
40
53
  if (a < 1) {
41
54
  // Algorithm GS
42
55
  const e = 1 + EXP_M1 * a;
43
56
  let x;
57
+ let p;
44
58
  for (;;) {
45
- const p = e * unifRand();
59
+ p = e * unifRand();
46
60
  if (p >= 1) {
47
61
  x = -Math.log((e - p) / a);
48
62
  if (expRand() >= (1 - a) * Math.log(x))
@@ -54,6 +68,10 @@ export function rgamma1(a, scale) {
54
68
  break;
55
69
  }
56
70
  }
71
+ // x = p^(1/a) (p < 1) can fall below the normal range, or to 0, although a large scale brings the variate back
72
+ // into it (R gives 0): scale p^(1/a) from the logs in double-double then (the acceptance above is unchanged)
73
+ if (x < 2 ** -1022 && scale > 1)
74
+ return ddExp(ddAdd(ddLog([scale, 0]), ddDivNum(ddLog([p, 0]), a)))[0];
57
75
  return scale * x;
58
76
  }
59
77
  // Algorithm GD. Step 1: rebuild s and d if the parameters changed
@@ -136,6 +154,7 @@ export function rgamma1(a, scale) {
136
154
  * @category Random numbers
137
155
  */
138
156
  export function rgamma(n, shape, options = {}) {
157
+ checkOptions(options, RGAMMA_KEYS, "rgamma"); // generated: option-keys.mjs
139
158
  const scale = gammaScale(options);
140
159
  return generate(n, () => rgamma1(shape, scale));
141
160
  }
@@ -144,9 +163,12 @@ export function rchisq1(df) {
144
163
  return NaN;
145
164
  return rgamma1(df / 2, 2);
146
165
  }
147
- /** One noncentral χ² variate: Poisson mixture (χ² with df + 2 × Poisson(ncp/2) degrees of freedom) */
166
+ /**
167
+ * One noncentral χ² variate: Poisson mixture (χ² with df + 2 × Poisson(ncp/2) degrees of freedom). df = Inf gives Inf
168
+ * after the Poisson (and χ²) variates, as R's rnchisq (which rejects only a NaN df); the central rchisq1 gives NaN there
169
+ */
148
170
  export function rnchisq1(df, ncp) {
149
- if (!Number.isFinite(df) || !Number.isFinite(ncp) || df < 0 || ncp < 0)
171
+ if (Number.isNaN(df) || !Number.isFinite(ncp) || df < 0 || ncp < 0)
150
172
  return NaN;
151
173
  if (ncp === 0)
152
174
  return df === 0 ? 0 : rgamma1(df / 2, 2);
@@ -175,6 +197,7 @@ export function rnchisq1(df, ncp) {
175
197
  * @category Random numbers
176
198
  */
177
199
  export function rchisq(n, df, options = {}) {
200
+ checkOptions(options, RCHISQ_KEYS, "rchisq"); // generated: option-keys.mjs
178
201
  const { ncp } = options;
179
202
  if (ncp === undefined)
180
203
  return generate(n, () => rchisq1(df));
@@ -197,6 +220,7 @@ export function rchisq(n, df, options = {}) {
197
220
  * @category Random numbers
198
221
  */
199
222
  export function rt(n, df, options = {}) {
223
+ checkOptions(options, RT_KEYS, "rt"); // generated: option-keys.mjs
200
224
  const { ncp } = options;
201
225
  if (ncp === undefined) {
202
226
  return generate(n, () => {
@@ -212,6 +236,10 @@ export function rt(n, df, options = {}) {
212
236
  if (Number.isNaN(ncp))
213
237
  return generate(n, () => NaN);
214
238
  const z = generate(n, () => rnorm1(ncp, 1));
239
+ // df = Inf: V / df is 1 in the limit, so T = Z + ncp ~ N(ncp, 1) (R gives NaN, as its rchisq(n, Inf) does). No χ²
240
+ // variates are drawn then, as R's rchisq(n, Inf) draws none, so the stream stays R's
241
+ if (df === Infinity)
242
+ return z;
215
243
  const v = rchisq(n, df);
216
244
  return z.map((zi, i) => zi / Math.sqrt(v[i] / df));
217
245
  }
@@ -233,6 +261,7 @@ export function rt(n, df, options = {}) {
233
261
  * @category Random numbers
234
262
  */
235
263
  export function rf(n, df1, df2, options = {}) {
264
+ checkOptions(options, RF_KEYS, "rf"); // generated: option-keys.mjs
236
265
  const { ncp } = options;
237
266
  if (ncp === undefined) {
238
267
  return generate(n, () => {
@@ -244,7 +273,17 @@ export function rf(n, df1, df2, options = {}) {
244
273
  });
245
274
  }
246
275
  // Noncentral F: as in R, generate n noncentral χ² variates first, then n χ² variates
247
- const x = rchisq(n, df1, { ncp });
248
- const y = rchisq(n, df2);
249
- return x.map((xi, i) => xi / df1 / (y[i] / df2));
276
+ // An infinite df makes that χ² over its df 1 in the limit (for a finite ncp >= 0: mean (df + ncp) / df, variance
277
+ // (2 df + 4 ncp) / df^2): F is then X / df1, df2 / Y or 1 (R gives NaN). The variates R draws are drawn, so the
278
+ // stream stays R's: the noncentral χ² with df1 = Inf draws its Poisson mixture (R's value Inf, used here only for
279
+ // its draws and NaN), the central one with df2 = Inf draws none
280
+ const x = df1 === Infinity
281
+ ? rchisq(n, df1, { ncp }).map((v) => (Number.isNaN(v) ? NaN : 1))
282
+ : rchisq(n, df1, { ncp }).map((v) => v / df1);
283
+ const y = df2 === Infinity ? generate(n, () => 1) : rchisq(n, df2).map((v) => v / df2);
284
+ // F needs df1 > 0 and df2 > 0 (the central branch gives NaN otherwise). R divides by df1 = 0 here and returns Inf or
285
+ // NaN depending on the draw; NaN throughout, with the same variates drawn (so the stream stays R's)
286
+ if (!(df1 > 0 && df2 > 0))
287
+ return x.map(() => NaN);
288
+ return x.map((xi, i) => xi / y[i]);
250
289
  }
@@ -6,8 +6,9 @@
6
6
  // The order in which uniforms are consumed and the parameter handling follow observed R output.
7
7
  import { unifRand } from "./rng.js";
8
8
  import { generate } from "./common.js";
9
+ import { roundHalfEven } from "../internal/integer.js";
9
10
  import { rbinom1 } from "./binomial.js";
10
- import { qhyper1 } from "../distributions/hypergeometric.js";
11
+ import { qhyper1, whiteFraction } from "../distributions/hypergeometric.js";
11
12
  const INT_MAX = 2147483647;
12
13
  const LN_SQRT_2PI = 0.918938533204672741780329736406;
13
14
  const DELTAL = 0.0078;
@@ -41,16 +42,18 @@ let a = 0, d = 0, xl = 0, xr = 0, kl = 0, kr = 0, lamdl = 0, lamdr = 0, p1 = 0,
41
42
  export function rhyper1(nn1in, nn2in, kkin) {
42
43
  if (!Number.isFinite(nn1in) || !Number.isFinite(nn2in) || !Number.isFinite(kkin))
43
44
  return NaN;
44
- nn1in = Math.round(nn1in);
45
- nn2in = Math.round(nn2in);
46
- kkin = Math.round(kkin);
45
+ // as R's R_forceint (nearbyint): halves go to the even integer (2.5 is 2, as in R; Math.round made it 3)
46
+ nn1in = roundHalfEven(nn1in);
47
+ nn2in = roundHalfEven(nn2in);
48
+ kkin = roundHalfEven(kkin);
47
49
  if (nn1in < 0 || nn2in < 0 || kkin < 0 || kkin > nn1in + nn2in)
48
50
  return NaN;
49
51
  if (nn1in >= INT_MAX || nn2in >= INT_MAX || kkin >= INT_MAX) {
50
52
  // Parameters beyond the integer range: Bernoulli for a single draw, otherwise invert via the quantile function
53
+ // (the white fraction without forming nn1 + nn2, which overflows near the largest double: it was 0)
51
54
  if (kkin === 1)
52
- return rbinom1(kkin, nn1in / (nn1in + nn2in));
53
- return qhyper1(unifRand(), nn1in, nn2in, kkin, false, false);
55
+ return rbinom1(kkin, whiteFraction(nn1in, nn2in));
56
+ return qhyper1(unifRand(), nn1in, nn2in, kkin, false, false, false);
54
57
  }
55
58
  const nn1 = nn1in;
56
59
  const nn2 = nn2in;
package/dist/random/mt.js CHANGED
@@ -44,7 +44,8 @@ export class MersenneTwister {
44
44
  /** One 32-bit unsigned integer */
45
45
  nextUint32() {
46
46
  const mt = this.mt;
47
- if (this.mti >= N) {
47
+ // (mti is 0 here only when a state with position 0 was set: R regenerates for it, as for 624; issue #90)
48
+ if (this.mti >= N || this.mti === 0) {
48
49
  if (this.mti === N + 1)
49
50
  this.sgenrand(4357);
50
51
  let kk = 0;
@@ -89,7 +90,21 @@ export class MersenneTwister {
89
90
  setRandomSeed(state) {
90
91
  if (state.length !== N + 2)
91
92
  throw new RangeError(`the random seed state must have ${N + 2} integers`);
92
- this.mti = state[1];
93
+ // the position must be an integer from 0 to 2^31 - 1, as R's integer .Random.seed holds it (getRandomSeed returns it
94
+ // in an Int32Array). 0, and a position past N, make the next draw regenerate, as in R. R takes a negative one as
95
+ // given and its first draw then reads that slot itself as a state word; a corrupted state is refused here instead
96
+ // of producing numbers from it
97
+ const mti = state[1];
98
+ if (!Number.isInteger(mti) || mti < 0 || mti > 2 ** 31 - 1) {
99
+ throw new RangeError("the position in the random seed state must be a non-negative 32-bit integer");
100
+ }
101
+ for (let i = 0; i < N; i++) {
102
+ const v = state[i + 2];
103
+ // 32-bit words, as R's integer .Random.seed holds them (signed or unsigned); others were reduced modulo 2^32
104
+ if (!Number.isInteger(v) || v < -(2 ** 31) || v >= 2 ** 32)
105
+ throw new RangeError("the random seed state must hold 32-bit integers");
106
+ }
107
+ this.mti = mti;
93
108
  for (let i = 0; i < N; i++)
94
109
  this.mt[i] = state[i + 2] >>> 0;
95
110
  }