@numero-uno-jpn/rstats 0.15.3 → 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 (285) hide show
  1. package/CHANGELOG.md +166 -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-VLUL2HFW.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 +24 -4
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +12 -4
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +5 -0
  52. package/dist/distributions/f.js +32 -17
  53. package/dist/distributions/gamma.js +27 -3
  54. package/dist/distributions/geometric.js +49 -13
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +2 -1
  58. package/dist/distributions/laplace.js +27 -6
  59. package/dist/distributions/logistic.js +4 -1
  60. package/dist/distributions/lognormal.js +8 -2
  61. package/dist/distributions/multinomial.js +54 -11
  62. package/dist/distributions/nbeta.js +62 -11
  63. package/dist/distributions/nchisq.js +30 -6
  64. package/dist/distributions/negbinomial.js +94 -17
  65. package/dist/distributions/normal.js +9 -4
  66. package/dist/distributions/nt.js +392 -17
  67. package/dist/distributions/pareto.js +4 -1
  68. package/dist/distributions/poisson.js +28 -3
  69. package/dist/distributions/signrank.js +7 -4
  70. package/dist/distributions/summary.js +450 -60
  71. package/dist/distributions/triangular.js +10 -5
  72. package/dist/distributions/tukey.js +5 -2
  73. package/dist/distributions/weibull.js +10 -0
  74. package/dist/distributions/wilcox.d.ts +9 -3
  75. package/dist/distributions/wilcox.js +155 -26
  76. package/dist/distributions.js +2 -2
  77. package/dist/htest/agreement.d.ts +3 -2
  78. package/dist/htest/agreement.js +76 -14
  79. package/dist/htest/ansariTest.d.ts +6 -1
  80. package/dist/htest/ansariTest.js +75 -8
  81. package/dist/htest/aov.d.ts +1 -1
  82. package/dist/htest/aov.js +48 -34
  83. package/dist/htest/binomTest.d.ts +5 -0
  84. package/dist/htest/binomTest.js +41 -17
  85. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  86. package/dist/htest/brunnerMunzelTest.js +7 -5
  87. package/dist/htest/chisqTest.d.ts +2 -1
  88. package/dist/htest/chisqTest.js +130 -43
  89. package/dist/htest/cor.d.ts +2 -1
  90. package/dist/htest/cor.js +17 -19
  91. package/dist/htest/core/ansari.d.ts +9 -0
  92. package/dist/htest/core/ansari.js +21 -1
  93. package/dist/htest/core/kolmogorov.d.ts +25 -0
  94. package/dist/htest/core/kolmogorov.js +123 -0
  95. package/dist/htest/core/mantelhaen.js +6 -4
  96. package/dist/htest/core/shapiro.d.ts +1 -1
  97. package/dist/htest/core/shapiro.js +5 -1
  98. package/dist/htest/dunnett.js +14 -5
  99. package/dist/htest/effectSize.d.ts +2 -0
  100. package/dist/htest/effectSize.js +91 -29
  101. package/dist/htest/fisherTest.d.ts +2 -2
  102. package/dist/htest/fisherTest.js +36 -18
  103. package/dist/htest/groups.d.ts +7 -0
  104. package/dist/htest/groups.js +21 -4
  105. package/dist/htest/ksTest.d.ts +3 -1
  106. package/dist/htest/ksTest.js +23 -2
  107. package/dist/htest/leveneTest.js +19 -3
  108. package/dist/htest/mantelhaenTest.js +125 -25
  109. package/dist/htest/mcnemarTest.js +32 -11
  110. package/dist/htest/multipleComparisons.d.ts +8 -1
  111. package/dist/htest/multipleComparisons.js +44 -21
  112. package/dist/htest/normalityTests.js +44 -10
  113. package/dist/htest/onewayTest.js +96 -5
  114. package/dist/htest/pAdjust.d.ts +3 -2
  115. package/dist/htest/pAdjust.js +38 -6
  116. package/dist/htest/pairwise.d.ts +1 -1
  117. package/dist/htest/pairwise.js +17 -15
  118. package/dist/htest/poissonTest.d.ts +1 -1
  119. package/dist/htest/poissonTest.js +111 -59
  120. package/dist/htest/polycor.js +27 -7
  121. package/dist/htest/power.d.ts +11 -1
  122. package/dist/htest/power.js +112 -8
  123. package/dist/htest/propTest.js +21 -4
  124. package/dist/htest/pwr.js +121 -24
  125. package/dist/htest/rankTests.js +29 -5
  126. package/dist/htest/tTest.js +44 -21
  127. package/dist/htest/trendTests.d.ts +7 -3
  128. package/dist/htest/trendTests.js +114 -20
  129. package/dist/htest/types.d.ts +5 -0
  130. package/dist/htest/types.js +7 -0
  131. package/dist/htest/varTest.js +45 -14
  132. package/dist/htest/wilcoxTest.js +114 -21
  133. package/dist/integrate/quadpack.js +27 -5
  134. package/dist/internal/covmat.d.ts +5 -0
  135. package/dist/internal/covmat.js +20 -0
  136. package/dist/internal/ddexp.d.ts +15 -1
  137. package/dist/internal/ddexp.js +59 -6
  138. package/dist/internal/discrete.d.ts +14 -0
  139. package/dist/internal/discrete.js +78 -5
  140. package/dist/internal/extremes.d.ts +9 -0
  141. package/dist/internal/extremes.js +24 -0
  142. package/dist/internal/fround.js +13 -4
  143. package/dist/internal/integer.d.ts +9 -0
  144. package/dist/internal/integer.js +12 -0
  145. package/dist/internal/invert.js +15 -2
  146. package/dist/internal/scaledInverse.d.ts +10 -0
  147. package/dist/internal/scaledInverse.js +22 -0
  148. package/dist/internal/seq.js +15 -2
  149. package/dist/internal/summary.d.ts +90 -0
  150. package/dist/internal/summary.js +458 -39
  151. package/dist/internal/uniroot.d.ts +7 -0
  152. package/dist/internal/uniroot.js +28 -3
  153. package/dist/linalg/basic.d.ts +3 -1
  154. package/dist/linalg/basic.js +51 -7
  155. package/dist/linalg/chol.js +4 -1
  156. package/dist/linalg/dot.d.ts +29 -0
  157. package/dist/linalg/dot.js +132 -0
  158. package/dist/linalg/eigen.d.ts +6 -1
  159. package/dist/linalg/eigen.js +71 -14
  160. package/dist/linalg/expm.d.ts +3 -2
  161. package/dist/linalg/expm.js +109 -15
  162. package/dist/linalg/kappa.js +58 -10
  163. package/dist/linalg/lu.d.ts +2 -1
  164. package/dist/linalg/lu.js +35 -5
  165. package/dist/linalg/matrix.d.ts +14 -0
  166. package/dist/linalg/matrix.js +24 -0
  167. package/dist/linalg/ops.js +60 -13
  168. package/dist/linalg/qr.d.ts +2 -1
  169. package/dist/linalg/qr.js +91 -23
  170. package/dist/linalg/schur.js +11 -3
  171. package/dist/linalg/solve.d.ts +6 -1
  172. package/dist/linalg/solve.js +147 -26
  173. package/dist/linalg/svd.d.ts +9 -2
  174. package/dist/linalg/svd.js +29 -11
  175. package/dist/linalg.js +2 -2
  176. package/dist/mixed.js +4 -4
  177. package/dist/models/anovaSequential.d.ts +16 -1
  178. package/dist/models/anovaSequential.js +124 -25
  179. package/dist/models/aovEz.js +140 -30
  180. package/dist/models/aovStrata.js +55 -22
  181. package/dist/models/carAnova.d.ts +1 -1
  182. package/dist/models/carAnova.js +83 -32
  183. package/dist/models/coxph.js +148 -66
  184. package/dist/models/estimable.d.ts +15 -0
  185. package/dist/models/estimable.js +68 -0
  186. package/dist/models/formula.d.ts +1 -1
  187. package/dist/models/formula.js +26 -8
  188. package/dist/models/glm.d.ts +35 -5
  189. package/dist/models/glm.js +398 -55
  190. package/dist/models/glmAnova.js +84 -13
  191. package/dist/models/glmConfint.d.ts +1 -1
  192. package/dist/models/glmConfint.js +115 -27
  193. package/dist/models/glmFamily.d.ts +10 -0
  194. package/dist/models/glmFamily.js +244 -40
  195. package/dist/models/lm.d.ts +12 -1
  196. package/dist/models/lm.js +235 -36
  197. package/dist/models/lmer.d.ts +20 -1
  198. package/dist/models/lmer.js +109 -27
  199. package/dist/models/lmerAnova.js +37 -4
  200. package/dist/models/lmerHypotheses.d.ts +6 -2
  201. package/dist/models/lmerHypotheses.js +14 -2
  202. package/dist/models/lmerTest.d.ts +9 -2
  203. package/dist/models/lmerTest.js +64 -19
  204. package/dist/models/mauchly.d.ts +4 -1
  205. package/dist/models/mauchly.js +34 -13
  206. package/dist/models/mixedStructure.js +6 -0
  207. package/dist/models/modelFrame.js +8 -2
  208. package/dist/models/modelMatrix.d.ts +3 -1
  209. package/dist/models/modelMatrix.js +40 -15
  210. package/dist/models/scaledTables.d.ts +8 -0
  211. package/dist/models/scaledTables.js +6 -0
  212. package/dist/models/survival.d.ts +6 -1
  213. package/dist/models/survival.js +67 -27
  214. package/dist/models/tiedTimes.d.ts +2 -0
  215. package/dist/models/tiedTimes.js +34 -0
  216. package/dist/numerics/deriv.d.ts +1 -1
  217. package/dist/numerics/deriv.js +64 -8
  218. package/dist/numerics/integrate.d.ts +9 -1
  219. package/dist/numerics/integrate.js +103 -16
  220. package/dist/numerics/interp.d.ts +8 -2
  221. package/dist/numerics/interp.js +352 -50
  222. package/dist/numerics/ode.js +55 -1
  223. package/dist/numerics.js +2 -2
  224. package/dist/optim/localmin.js +4 -0
  225. package/dist/optim/optim.d.ts +3 -1
  226. package/dist/optim/optim.js +80 -8
  227. package/dist/random/beta.js +53 -4
  228. package/dist/random/binomial.d.ts +14 -3
  229. package/dist/random/binomial.js +59 -24
  230. package/dist/random/continuous.js +33 -5
  231. package/dist/random/extra.js +42 -9
  232. package/dist/random/gamma.d.ts +4 -1
  233. package/dist/random/gamma.js +36 -8
  234. package/dist/random/hyper.js +9 -6
  235. package/dist/random/mt.js +17 -2
  236. package/dist/random/poisson.js +26 -3
  237. package/dist/random/r2dtable.d.ts +8 -1
  238. package/dist/random/r2dtable.js +24 -3
  239. package/dist/random/rank.d.ts +2 -0
  240. package/dist/random/rank.js +44 -4
  241. package/dist/random/sample.d.ts +12 -2
  242. package/dist/random/sample.js +57 -20
  243. package/dist/random/streams.js +4 -2
  244. package/dist/rstats.js +14 -14
  245. package/dist/special/besselIK.d.ts +12 -0
  246. package/dist/special/besselIK.js +168 -23
  247. package/dist/special/besselJY.d.ts +11 -1
  248. package/dist/special/besselJY.js +127 -19
  249. package/dist/special/besselSeries.d.ts +27 -0
  250. package/dist/special/besselSeries.js +45 -2
  251. package/dist/special/beta.js +4 -1
  252. package/dist/special/choose.js +17 -8
  253. package/dist/special/dd.js +122 -18
  254. package/dist/special/extra.js +14 -2
  255. package/dist/special/gamma.js +11 -2
  256. package/dist/special/incbet.js +30 -4
  257. package/dist/special/incbetTemme.d.ts +7 -0
  258. package/dist/special/incbetTemme.js +45 -12
  259. package/dist/special/loader.d.ts +1 -1
  260. package/dist/special/loader.js +117 -20
  261. package/dist/special/log1pmx.js +4 -0
  262. package/dist/special.js +2 -2
  263. package/dist/tests.js +11 -11
  264. package/llms.txt +12 -6
  265. package/package.json +1 -1
  266. package/dist/chunks/chunk-3THFTB36.js +0 -2
  267. package/dist/chunks/chunk-3TSWYE5L.js +0 -2
  268. package/dist/chunks/chunk-3WPU6LGK.js +0 -2
  269. package/dist/chunks/chunk-5ITR67MB.js +0 -2
  270. package/dist/chunks/chunk-5NRFU6F6.js +0 -2
  271. package/dist/chunks/chunk-E2LCSVQV.js +0 -2
  272. package/dist/chunks/chunk-FCNVTIPJ.js +0 -2
  273. package/dist/chunks/chunk-FKAKALOZ.js +0 -2
  274. package/dist/chunks/chunk-HD73UKPT.js +0 -2
  275. package/dist/chunks/chunk-IUULP3LE.js +0 -2
  276. package/dist/chunks/chunk-JQG3YQOC.js +0 -2
  277. package/dist/chunks/chunk-KT66SB7R.js +0 -2
  278. package/dist/chunks/chunk-MAUAOQG3.js +0 -2
  279. package/dist/chunks/chunk-MDYE7QP2.js +0 -2
  280. package/dist/chunks/chunk-NM3Z2UBQ.js +0 -2
  281. package/dist/chunks/chunk-PMJI5QO6.js +0 -3
  282. package/dist/chunks/chunk-UF7KOTHF.js +0 -3
  283. package/dist/chunks/chunk-UOE57JGT.js +0 -2
  284. package/dist/chunks/chunk-USPEBXSR.js +0 -2
  285. package/dist/chunks/chunk-ZIX7NYQF.js +0 -2
package/dist/numerics.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.15.3 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{a as $,b as T,c as D,d as F,e as O}from"./chunks/chunk-PMJI5QO6.js";import"./chunks/chunk-ZIX7NYQF.js";import{a as k,f as j}from"./chunks/chunk-MAUAOQG3.js";import"./chunks/chunk-IUULP3LE.js";import{f as S}from"./chunks/chunk-3WPU6LGK.js";import"./chunks/chunk-VLUL2HFW.js";import"./chunks/chunk-KT66SB7R.js";function M(o,l,t="mean"){if(o.length!==l.length)throw new RangeError("'x' and 'y' lengths differ");let n=[];for(let r=0;r<o.length;r++)!Number.isNaN(o[r])&&!Number.isNaN(l[r])&&n.push(r);n.sort((r,s)=>o[r]-o[s]);let e=typeof t=="function"?t:t==="min"?r=>Math.min(...r):t==="max"?r=>Math.max(...r):S,a=[],f=[];for(let r=0;r<n.length;){let s=o[n[r]],c=r+1;for(;c<n.length&&o[n[c]]===s;)c++;a.push(s),f.push(c-r===1?l[n[r]]:e(n.slice(r,c).map(i=>l[i]))),r=c}return{x:a,y:f}}function X(o,l,t,n){let e=(n-o[t])/(o[t+1]-o[t]);return l[t]+(l[t+1]-l[t])*e}function J(o,l,t){let n=(e,a)=>e===0?0:e*a;return n(1-t,o[l])+n(t,o[l+1])}function P(o,l,t={}){let{method:n="linear",n:e=50,f:a=0,rule:f=1,ties:r="mean"}=t,s=M(o,l,r),c=s.x.length;if(c<=1&&n==="linear")throw new RangeError("need at least two non-NA values to interpolate");if(c===0)throw new RangeError("zero non-NA points");if(n==="constant"&&!(a>=0&&a<=1))throw new RangeError("approx(): invalid f value");let[i,p]=typeof f=="number"?[f,f]:f,d=t.yleft??(i===1?NaN:s.y[0]),h=t.yright??(p===1?NaN:s.y[c-1]),m;if(t.xout!==void 0)m=Array.from(t.xout);else{if(e<=0)throw new RangeError("'approx' requires n >= 1");m=k(s.x[0],s.x[c-1],e)}let g=s.x,u=s.y,w=j(m,g),y=m.map((b,A)=>{let R=w[A];if(Number.isNaN(R))return NaN;if(R===0)return d;let E=R-1;return b===g[E]?u[E]:R===c?h:n==="linear"?X(g,u,E,b):J(u,E,a)});return{x:m,y}}function v(o,l){let t=o.length,n=new Array(t).fill(0),e=new Array(t).fill(0),a=new Array(t).fill(0);if(t<2)return{b:n,c:e,d:a};if(t<3)return n[0]=(l[1]-l[0])/(o[1]-o[0]),n[1]=n[0],{b:n,c:e,d:a};let f=t-1;a[0]=o[1]-o[0],e[1]=(l[1]-l[0])/a[0];for(let r=1;r<f;r++)a[r]=o[r+1]-o[r],n[r]=2*(a[r-1]+a[r]),e[r+1]=(l[r+1]-l[r])/a[r],e[r]=e[r+1]-e[r];n[0]=-a[0],n[f]=-a[t-2],e[0]=0,e[f]=0,t>3&&(e[0]=e[2]/(o[3]-o[1])-e[1]/(o[2]-o[0]),e[f]=e[t-2]/(o[f]-o[t-3])-e[t-3]/(o[t-2]-o[t-4]),e[0]=e[0]*a[0]*a[0]/(o[3]-o[0]),e[f]=-e[f]*a[t-2]*a[t-2]/(o[f]-o[t-4]));for(let r=1;r<t;r++){let s=a[r-1]/n[r-1];n[r]=n[r]-s*a[r-1],e[r]=e[r]-s*e[r-1]}e[f]=e[f]/n[f];for(let r=t-2;r>=0;r--)e[r]=(e[r]-a[r]*e[r+1])/n[r];n[f]=(l[f]-l[t-2])/a[t-2]+a[t-2]*(e[t-2]+2*e[f]);for(let r=0;r<f;r++)n[r]=(l[r+1]-l[r])/a[r]-a[r]*(e[r+1]+2*e[r]),a[r]=(e[r+1]-e[r])/a[r],e[r]=3*e[r];return e[f]=3*e[f],a[f]=a[t-2],{b:n,c:e,d:a}}function z(o,l,t){let n=o.length,e=new Array(n).fill(0),a=new Array(n).fill(0),f=new Array(n).fill(0);for(let r=0;r<n-1;r++){let s=o[r+1]-o[r];e[r]=(l[r+1]-l[r])/s-s*(t[r+1]+2*t[r]),a[r]=3*t[r],f[r]=(t[r+1]-t[r])/s}return{b:e,c:a,d:f}}function Y(o,l){let t=o.length;if(t<3)return v(o,l);let n=Array.from({length:t-1},(c,i)=>o[i+1]-o[i]),e=n.map((c,i)=>(l[i+1]-l[i])/c),a=new Array(t).fill(0),f=new Array(t).fill(0);for(let c=1;c<t-1;c++)a[c]=2*(n[c-1]+n[c]),f[c]=e[c]-e[c-1];for(let c=2;c<t-1;c++){let i=n[c-1]/a[c-1];a[c]=a[c]-i*n[c-1],f[c]=f[c]-i*f[c-1]}let r=new Array(t).fill(0);r[t-2]=f[t-2]/a[t-2];for(let c=t-3;c>=1;c--)r[c]=(f[c]-n[c]*r[c+1])/a[c];let s=z(o,l,r);return s.b[t-1]=e[t-2]+n[t-2]*r[t-2],s}function B(o,l){let t=o.length;if(l[0]!==l[t-1])throw new RangeError("periodic spline needs y[1] == y[n]");if(t<3)return{b:new Array(t).fill(0),c:new Array(t).fill(0),d:new Array(t).fill(0)};let n=t-1,e=Array.from({length:n},(u,w)=>o[w+1]-o[w]),a=e.map((u,w)=>(l[w+1]-l[w])/u),f=u=>u===0?n-1:u-1,r=Array.from({length:n},(u,w)=>2*(e[f(w)]+e[w])),s=Array.from({length:n},(u,w)=>a[w]-a[f(w)]),c=e.slice(),i=new Array(n).fill(0);i[0]=e[n-1],i[n-2]=i[n-2]+e[n-2];let p=i[0],d=r[n-1],h=s[n-1];for(let u=0;u<n-1;u++){if(u+1<n-1){let y=e[u]/r[u];r[u+1]=r[u+1]-y*c[u],i[u+1]=i[u+1]-y*i[u],s[u+1]=s[u+1]-y*s[u]}let w=p/r[u];d-=w*i[u],h-=w*s[u],u+1<n-1&&(p=(u+1===n-2?e[n-2]:0)-w*c[u])}let m=new Array(t).fill(0);m[n-1]=h/d;for(let u=n-2;u>=0;u--){let w=s[u]-i[u]*m[n-1]-(u<n-2?c[u]*m[u+1]:0);m[u]=w/r[u]}m[t-1]=m[0];let g=z(o,l,m);return g.b[t-1]=g.b[0],g.c[t-1]=g.c[0],g.d[t-1]=g.d[0],g}function G(o,l){let t=o.length,{b:n,c:e,d:a}=v(o,l);if(t<2)return{b:n,c:e,d:a};let f=Array.from({length:t-1},(s,c)=>(l[c+1]-l[c])/(o[c+1]-o[c]));for(let s=0;s<t;s++){let c=f[s===0?0:s-1],i=f[s===t-1?t-2:s],p=Math.min(Math.abs(c),Math.abs(i)),d=c*i>0?i>0:n[s]>=0;n[s]=d?Math.min(Math.max(0,n[s]),3*p):Math.max(Math.min(0,n[s]),-3*p)}for(let s=0;s<t-1;s++){let c=o[s+1]-o[s],i=(l[s+1]-l[s])/c;e[s]=(3*i-2*n[s]-n[s+1])/c,a[s]=(n[s]+n[s+1]-2*i)/(c*c)}let r=o[t-1]-o[t-2];return e[t-1]=(n[t-2]+2*n[t-1]-3*(l[t-1]-l[t-2])/r)/r,a[t-1]=a[t-2],{b:n,c:e,d:a}}function q(o,l,t,n){let e=M(o,l,n),a=e.x.length;if(a===0)throw new RangeError("zero non-NA points");t==="periodic"&&e.y[a-1]!==e.y[0]&&(e.y[a-1]=e.y[0]),t==="hyman"&&K(e.y);let f=t==="fmm"?v(e.x,e.y):t==="natural"?Y(e.x,e.y):t==="periodic"?B(e.x,e.y):t==="hyman"?G(e.x,e.y):(()=>{throw new RangeError(`invalid spline method '${String(t)}'`)})();return{method:t,...e,...f}}function K(o){let l=!0,t=!0;for(let n=1;n<o.length;n++){let e=o[n]-o[n-1];e>=0||(l=!1),e<=0||(t=!1)}if(!l&&!t)throw new RangeError("'y' must be increasing or decreasing")}function C(o){let l=Math.trunc(o);if(!(l>=0&&l<=3))throw new RangeError("'deriv' must be between 0 and 3");return l}function H(o,l,t){let n=C(t),{x:e,y:a,b:f,c:r,d:s,method:c}=o,i=e.length,p=c==="natural",d=e[i-1]-e[0],h=0;return Array.from(l,m=>{let g=m;if(c==="periodic"&&i>1){let y=(g-e[0])%d;y<0&&(y+=d),g=e[0]+y}if(p&&n>0&&g<=e[0])return n===1?f[0]:0;if(!(e[h]<=g&&(h===i-1||g<=e[h+1]))){let y=0,b=i;for(;b-y>1;){let A=y+b>>1;e[A]<=g?y=A:b=A}h=y}let u=g-e[h],w=p&&g<e[0]?0:s[h];switch(n){case 0:return a[h]+u*(f[h]+u*(r[h]+u*w));case 1:return f[h]+u*(2*r[h]+u*(3*w));case 2:return 2*r[h]+u*(6*w);default:return 6*w}})}function Q(o,l,t={}){let{method:n="fmm",ties:e="mean"}=t,a=q(o,l,n,e),f;if(t.xout!==void 0)f=Array.from(t.xout);else{let r=a.x.length,s=t.n??3*r;if(s<=0)throw new RangeError("'spline' requires n >= 1");f=k(t.xmin??a.x[0],t.xmax??a.x[r-1],s)}return{x:f,y:H(a,f,0)}}function U(o,l,t={}){let{method:n="fmm",ties:e="mean"}=t;if(n==="monoH.FC"){let f=M(o,l,e);if(f.x.length===0)throw new RangeError("zero non-NA points");let r=V(f.x,f.y);return(s,c=0)=>I(f.x,f.y,r,s,c)}let a=q(o,l,n,e);return(f,r=0)=>H(a,f,r)}function V(o,l){let t=o.length;if(t<2)throw new RangeError("length(m) must be at least two");let n=Array.from({length:t-1},(a,f)=>(l[f+1]-l[f])/(o[f+1]-o[f])),e=Array.from({length:t},(a,f)=>f===0?n[0]:f===t-1?n[t-2]:(n[f-1]+n[f])/2);for(let a=0;a<t-1;a++){let f=n[a];if(f===0){e[a]=0,e[a+1]=0;continue}let r=e[a]/f,s=e[a+1]/f,c=2*r+s-3,i=r+2*s-3;if(c>0&&i>0&&r*(c+i)<c*c){let p=3*f/Math.sqrt(r*r+s*s);e[a]=p*r,e[a+1]=p*s}}return e}function I(o,l,t,n,e){let a=C(e),f=o.length;return Array.from(n,r=>{if(Number.isNaN(r))return NaN;let s=0,c=f;for(;s<c;){let A=s+c>>1;o[A]<=r?s=A+1:c=A}let i=s;if(i===0||i===f){let A=i===0?0:f-1;return a===0?l[A]+t[A]*(r-o[A]):a===1?t[A]:0}let p=o[i-1],d=o[i]-p,h=(r-p)/d,m=h-1,g=l[i-1],u=l[i],w=t[i-1],y=t[i],b=(u-g)/d;switch(a){case 0:{let A=h*h*(3-2*h);return g*(1-A)+d*w*(h*m*m)+u*A+d*y*(h*h*m)}case 1:return b*(-6*h*m)+w*(m*(3*h-1))+y*(h*(3*h-2));case 2:return(b*(6-12*h)+w*(6*h-4)+y*(6*h-2))/d;default:return(-12*b+6*w+6*y)/(d*d)}})}function W(o,l,t){let n=o.length;if(l.length!==n||t.length!==n)throw new RangeError("'x', 'y' and 'm' must have the same length");let e=Array.from({length:n},(s,c)=>c).sort((s,c)=>o[s]-o[c]),a=e.map(s=>o[s]),f=e.map(s=>l[s]),r=e.map(s=>t[s]);for(let s=1;s<n;s++)if(!(a[s]-a[s-1]>0))throw new RangeError("'x' must be *strictly* increasing (non - NA)");return(s,c=0)=>I(a,f,r,s,c)}function Z(o,l,t){let n=Array.from(o),e=Array.from(l),a=n.length;if(e.length!==a)throw new RangeError("'xi' and 'yi' must have the same length");let f=Array.from(t),r=Math.min(...n),s=Math.max(...n);if(f.some(i=>i<r||i>s))throw new RangeError("Some interpolation points outside the nodes.");let c=n.map((i,p)=>{let d=1;for(let h=0;h<a;h++)h!==p&&(d*=i-n[h]);return 1/d});return f.map(i=>{let p=0,d=0,h=n.lastIndexOf(i);if(h>=0)return e[h];for(let m=0;m<a;m++){let g=i-n[m],u=c[m]/g;p+=u*e[m],d+=u}return p/d})}function tt(o,l,t,n){let e=Array.from(o),a=Array.from(l),f=Array.from(t),r=e.length;if(a.length!==r||f.length!==r)throw new RangeError("'xi', 'yi' and 'di' must have the same length");let s=e.flatMap(h=>[h,h]),c=2*r,i=a.flatMap(h=>[h,h]),p=[i[0]],d=i.slice();for(let h=1;h<c;h++){let m=[];for(let g=0;g<c-h;g++)h===1&&s[g+1]===s[g]?m.push(f[g>>1]):m.push((d[g+1]-d[g])/(s[g+h]-s[g]));p.push(m[0]),d=m}return Array.from(n,h=>{let m=p[c-1];for(let g=c-2;g>=0;g--)m=m*(h-s[g])+p[g];return m})}function nt(o,l,t,n=[],e={}){let a=e.method??"rk4";if(a!=="euler"&&a!=="rk2"&&a!=="rk4")throw new RangeError(`unknown method '${String(a)}'`);let f=[...n],r=o.length,s=(d,h)=>{let m=Array.from(t(d,h,f));if(m.length!==r)throw new RangeError(`The number of derivatives returned by func() (${m.length}) must equal the length of the initial conditions vector (${r})`);return m},c=(d,h,m)=>d.map((g,u)=>g+h*m[u]),i=[...o],p=[];if(l.length===0)return p;p.push([l[0],...i]);for(let d=1;d<l.length;d++){let h=l[d-1],m=l[d]-h,g=s(h,i);if(a==="euler")i=c(i,m,g);else if(a==="rk2"){let u=s(h+m,c(i,m,g));i=i.map((w,y)=>w+m*(.5*g[y]+.5*u[y]))}else{let u=s(h+m/2,c(i,m/2,g)),w=s(h+m/2,c(i,m/2,u)),y=s(h+m,c(i,m,w));i=i.map((b,A)=>b+m/6*(g[A]+2*u[A]+2*w[A]+y[A]))}p.push([l[d],...i])}return p}function _(o,l,t){let n=l.eps??1e-4,e=l.d??t,a=l.zeroTol??Math.sqrt(Number.EPSILON/7e-7),f=l.r??4;if(!(Number.isInteger(f)&&f>=1))throw new RangeError("'r' must be a positive integer");return{eps:n,r:f,h0:o.map(r=>Math.abs(e*r)+(Math.abs(r)<a?n:0))}}function x(o){let l=[...o];for(let t=1;t<l.length;t++){let n=4**t;for(let e=0;e<l.length-t;e++)l[e]=(l[e+1]*n-l[e])/(n-1)}return l[0]}function N(o,l,t){let n=[...o];return n[l]=n[l]+t,n}function L(o){let l=o.method??"Richardson";if(l!=="Richardson"&&l!=="simple")throw new RangeError(`unknown method "${String(l)}" (expected "Richardson" or "simple")`);return l}function rt(o,l,t={}){let n=[...l],e=n.length;if(L(t)==="simple"){let s=t.eps??1e-4,c=o([...n]);return n.map((i,p)=>(o(N(n,p,s))-c)/s)}let{r:a,h0:f}=_(n,t,1e-4),r=[];for(let s=0;s<e;s++){let c=[],i=f[s];for(let p=0;p<a;p++){if(p>0&&Math.abs(c[p-1])<1e-20?c.push(0):c.push((o(N(n,s,i))-o(N(n,s,-i)))/(2*i)),Number.isNaN(c[p]))throw new RangeError(`func returned NaN at step ${i} from x`);i/=2}r.push(x(c))}return r}function et(o,l,t={}){let n=[...l],e=n.length,a=Array.from(o([...n])),f=a.map(()=>new Array(e).fill(NaN));if(L(t)==="simple"){let c=t.eps??1e-4;for(let i=0;i<e;i++){let p=o(N(n,i,c));a.forEach((d,h)=>f[h][i]=(p[h]-d)/c)}return f}let{r,h0:s}=_(n,t,1e-4);for(let c=0;c<e;c++){let i=a.map(()=>[]),p=s[c];for(let d=0;d<r;d++){let h=o(N(n,c,p)),m=o(N(n,c,-p));a.forEach((g,u)=>i[u].push((h[u]-m[u])/(2*p))),p/=2}a.forEach((d,h)=>f[h][c]=x(i[h]))}return f}function ot(o,l,t={}){if((t.method??"Richardson")!=="Richardson")throw new RangeError('hessian supports only method "Richardson"');let n=[...l],e=n.length,{r:a,h0:f}=_(n,t,.1),r=o([...n]),s=[];for(let i=0;i<e;i++){let p=[],d=f[i];for(let h=0;h<a;h++)p.push((o(N(n,i,d))-2*r+o(N(n,i,-d)))/d**2),d/=2;s.push(x(p))}let c=n.map(()=>new Array(e).fill(NaN));for(let i=0;i<e;i++){c[i][i]=s[i];for(let p=0;p<i;p++){let d=[],h=f[i],m=f[p];for(let g=0;g<a;g++){let u=N(N(n,i,h),p,m),w=N(N(n,i,-h),p,-m);d.push((o(u)-2*r+o(w)-s[i]*h**2-s[p]*m**2)/(2*h*m)),h/=2,m/=2}c[i][p]=c[p][i]=x(d)}}return c}export{P as approx,Z as barylag,rt as grad,tt as hermiteInterp,ot as hessian,$ as integrate,et as jacobian,nt as ode,O as optim,F as optimHess,T as optimize,Q as spline,U as splinefun,W as splinefunH,D as uniroot};
1
+ /*! rStats.js 0.16.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{a as rt,b as ot,c as st,e as it,f as at}from"./chunks/chunk-JBCA56ZS.js";import"./chunks/chunk-5UQCRBAG.js";import{a as D,f as V}from"./chunks/chunk-KAZRWIB5.js";import"./chunks/chunk-SYWOBOTR.js";import"./chunks/chunk-YRZWONZB.js";import{a as $,b as U,c as O}from"./chunks/chunk-W26LRYOJ.js";import{s as y,t as C,v as Q}from"./chunks/chunk-GM53LWSR.js";function H(o,i,e="mean"){if(o.length!==i.length)throw new RangeError("'x' and 'y' lengths differ");let t=[];for(let r=0;r<o.length;r++)!Number.isNaN(o[r])&&!Number.isNaN(i[r])&&t.push(r);t.sort((r,c)=>o[r]-o[c]);let n=typeof e=="function"?e:e==="min"?r=>O(r):e==="max"?r=>$(r):Q,s=[],u=[];for(let r=0;r<t.length;){let c=o[t[r]],f=r+1;for(;f<t.length&&o[t[f]]===c;)f++;s.push(c),u.push(f-r===1?i[t[r]]:n(t.slice(r,f).map(a=>i[a]))),r=f}return{x:s,y:u}}function ct(o,i,e,t){let n=(t-o[e])/(o[e+1]-o[e]);(!Number.isFinite(o[e+1]-o[e])||!Number.isFinite(t-o[e]))&&(n=(t/2-o[e]/2)/(o[e+1]/2-o[e]/2));let s=i[e+1]-i[e];return!Number.isFinite(s)&&Number.isFinite(i[e])&&Number.isFinite(i[e+1])?2*(i[e]/2+(i[e+1]/2-i[e]/2)*n):i[e]+s*n}function W(o,i,e){let t=i-o;return!Number.isFinite(t)&&Number.isFinite(o)&&Number.isFinite(i)?2*((i/2-o/2)/e):t/e}function _(o,i,e){let t=1,n=e;for(let s of o){if(s===0)return 0*t;let u=Math.floor(Math.log2(Math.abs(s)));t*=y(s,-u),n+=u}for(let s of i){let u=Math.floor(Math.log2(Math.abs(s)));t/=y(s,-u),n-=u}return C(t,n)}function ft(o,i,e){let t=(n,s)=>n===0?0:n*s;return t(1-e,o[i])+t(e,o[i+1])}function ut(o){if(o===void 0)return"linear";if(typeof o=="string"&&o.length>0){let i=["linear","constant"].filter(e=>e.startsWith(o));if(i.length===1)return i[0]}throw new RangeError("invalid interpolation method")}function lt(o){let i=typeof o=="number"?[o]:Array.isArray(o)?o:[],e=t=>t===1||t===2;if(i.length<1||i.length>2||!i.every(e))throw new RangeError("'rule' must be 1 or 2, or a pair of them");return[i[0],i[i.length-1]]}function ht(o,i,e={}){let{n:t=50,f:n=0,rule:s=1,ties:u="mean"}=e,r=ut(e.method),[c,f]=lt(s),a=H(o,i,u),p=a.x.length;if(p<=1&&r==="linear")throw new RangeError("need at least two non-NA values to interpolate");if(p===0)throw new RangeError("zero non-NA points");if(r==="constant"&&!(n>=0&&n<=1))throw new RangeError("approx(): invalid f value");let g=e.yleft??(c===1?NaN:a.y[0]),h=e.yright??(f===1?NaN:a.y[p-1]),m;if(e.xout!==void 0)m=Array.from(e.xout);else{if(!Number.isFinite(t)&&!Number.isNaN(t))throw new RangeError("'length.out' must be a finite number");if(!(t>0))throw new RangeError("'approx' requires n >= 1");m=D(a.x[0],a.x[p-1],t)}let d=a.x,l=a.y,b=V(m,d),N=m.map((M,A)=>{let R=b[A];if(Number.isNaN(R))return NaN;if(R===0)return g;let E=R-1;return M===d[E]?l[E]:R===p?h:r==="linear"?ct(d,l,E,M):ft(l,E,n)});return{x:m,y:N}}function J(o,i){let e=o.length,t=new Array(e).fill(0),n=new Array(e).fill(0),s=new Array(e).fill(0);if(e<2)return{b:t,c:n,d:s};if(e<3)return t[0]=W(i[0],i[1],o[1]-o[0]),t[1]=t[0],{b:t,c:n,d:s};let u=e-1;s[0]=o[1]-o[0],n[1]=(i[1]-i[0])/s[0];for(let r=1;r<u;r++)s[r]=o[r+1]-o[r],t[r]=2*(s[r-1]+s[r]),n[r+1]=(i[r+1]-i[r])/s[r],n[r]=n[r+1]-n[r];t[0]=-s[0],t[u]=-s[e-2],n[0]=0,n[u]=0,e>3&&(n[0]=n[2]/(o[3]-o[1])-n[1]/(o[2]-o[0]),n[u]=n[e-2]/(o[u]-o[e-3])-n[e-3]/(o[e-2]-o[e-4]),n[0]=n[0]*s[0]*s[0]/(o[3]-o[0]),n[u]=-n[u]*s[e-2]*s[e-2]/(o[u]-o[e-4]));for(let r=1;r<e;r++){let c=s[r-1]/t[r-1];t[r]=t[r]-c*s[r-1],n[r]=n[r]-c*n[r-1]}n[u]=n[u]/t[u];for(let r=e-2;r>=0;r--)n[r]=(n[r]-s[r]*n[r+1])/t[r];t[u]=(i[u]-i[e-2])/s[e-2]+s[e-2]*(n[e-2]+2*n[u]);for(let r=0;r<u;r++)t[r]=(i[r+1]-i[r])/s[r]-s[r]*(n[r+1]+2*n[r]),s[r]=(n[r+1]-n[r])/s[r],n[r]=3*n[r];return n[u]=3*n[u],s[u]=s[e-2],{b:t,c:n,d:s}}function X(o,i,e){let t=o.length,n=new Array(t).fill(0),s=new Array(t).fill(0),u=new Array(t).fill(0);for(let r=0;r<t-1;r++){let c=o[r+1]-o[r];n[r]=(i[r+1]-i[r])/c-c*(e[r+1]+2*e[r]),s[r]=3*e[r],u[r]=(e[r+1]-e[r])/c}return{b:n,c:s,d:u}}function mt(o,i){let e=o.length;if(e<3)return J(o,i);let t=Array.from({length:e-1},(f,a)=>o[a+1]-o[a]),n=t.map((f,a)=>(i[a+1]-i[a])/f),s=new Array(e).fill(0),u=new Array(e).fill(0);for(let f=1;f<e-1;f++)s[f]=2*(t[f-1]+t[f]),u[f]=n[f]-n[f-1];for(let f=2;f<e-1;f++){let a=t[f-1]/s[f-1];s[f]=s[f]-a*t[f-1],u[f]=u[f]-a*u[f-1]}let r=new Array(e).fill(0);r[e-2]=u[e-2]/s[e-2];for(let f=e-3;f>=1;f--)r[f]=(u[f]-t[f]*r[f+1])/s[f];let c=X(o,i,r);return c.b[e-1]=n[e-2]+t[e-2]*r[e-2],c}function pt(o,i){let e=o.length;if(i[0]!==i[e-1])throw new RangeError("periodic spline needs y[1] == y[n]");if(e<3)return{b:new Array(e).fill(0),c:new Array(e).fill(0),d:new Array(e).fill(0)};let t=e-1,n=Array.from({length:t},(l,b)=>o[b+1]-o[b]),s=n.map((l,b)=>(i[b+1]-i[b])/l),u=l=>l===0?t-1:l-1,r=Array.from({length:t},(l,b)=>2*(n[u(b)]+n[b])),c=Array.from({length:t},(l,b)=>s[b]-s[u(b)]),f=n.slice(),a=new Array(t).fill(0);a[0]=n[t-1],a[t-2]=a[t-2]+n[t-2];let p=a[0],g=r[t-1],h=c[t-1];for(let l=0;l<t-1;l++){if(l+1<t-1){let N=n[l]/r[l];r[l+1]=r[l+1]-N*f[l],a[l+1]=a[l+1]-N*a[l],c[l+1]=c[l+1]-N*c[l]}let b=p/r[l];g-=b*a[l],h-=b*c[l],l+1<t-1&&(p=(l+1===t-2?n[t-2]:0)-b*f[l])}let m=new Array(e).fill(0);m[t-1]=h/g;for(let l=t-2;l>=0;l--){let b=c[l]-a[l]*m[t-1]-(l<t-2?f[l]*m[l+1]:0);m[l]=b/r[l]}m[e-1]=m[0];let d=X(o,i,m);return d.b[e-1]=d.b[0],d.c[e-1]=d.c[0],d.d[e-1]=d.d[0],d}function bt(o,i){let e=o.length,{b:t,c:n,d:s}=J(o,i);if(e<2)return{b:t,c:n,d:s};let u=Array.from({length:e-1},(c,f)=>(i[f+1]-i[f])/(o[f+1]-o[f]));for(let c=0;c<e;c++){let f=u[c===0?0:c-1],a=u[c===e-1?e-2:c],p=Math.min(Math.abs(f),Math.abs(a)),g=f>0&&a>0||f<0&&a<0?a>0:t[c]>=0;t[c]=g?Math.min(Math.max(0,t[c]),3*p):Math.max(Math.min(0,t[c]),-3*p)}for(let c=0;c<e-1;c++){let f=o[c+1]-o[c],a=(i[c+1]-i[c])/f;n[c]=(3*a-2*t[c]-t[c+1])/f,s[c]=(t[c]+t[c+1]-2*a)/(f*f)}let r=o[e-1]-o[e-2];return n[e-1]=(t[e-2]+2*t[e-1]-3*(i[e-1]-i[e-2])/r)/r,s[e-1]=s[e-2],{b:t,c:n,d:s}}function q(o){let i=o.length;return i<2||!o.every(Number.isFinite)||Number.isFinite(o[i-1]-o[0])?0:Math.floor(Math.log2($(o.map(Math.abs))))}function L(o,i,e,t){let n=H(o,i,t),s=n.x.length;if(s===0)throw new RangeError("zero non-NA points");e==="periodic"&&n.y[s-1]!==n.y[0]&&(n.y[s-1]=n.y[0]),e==="hyman"&&gt(n.y);let u=e==="fmm"?J(n.x,n.y):e==="natural"?mt(n.x,n.y):e==="periodic"?pt(n.x,n.y):e==="hyman"?bt(n.x,n.y):(()=>{throw new RangeError(`invalid spline method '${String(e)}'`)})();return{method:e,...n,...u}}function gt(o){let i=!0,e=!0;for(let t=1;t<o.length;t++){let n=o[t]-o[t-1];n>=0||(i=!1),n<=0||(e=!1)}if(!i&&!e)throw new RangeError("'y' must be increasing or decreasing")}function B(o){let i=Math.trunc(o);if(!(i>=0&&i<=3))throw new RangeError("'deriv' must be between 0 and 3");return i}function P(o,i,e){let t=B(e),{x:n,y:s,b:u,c:r,d:c,method:f}=o,a=n.length,p=f==="natural",g=n[a-1]-n[0],h=0;return Array.from(i,m=>{let d=m;if(f==="periodic"&&a>1){let N=(d-n[0])%g;N<0&&(N+=g),d=n[0]+N}if(p&&t>0&&d<=n[0])return t===1?u[0]:0;if(!(n[h]<=d&&(h===a-1||d<=n[h+1]))){let N=0,M=a;for(;M-N>1;){let A=N+M>>1;n[A]<=d?N=A:M=A}h=N}let l=d-n[h],b=p&&d<n[0]?0:c[h];switch(t){case 0:return s[h]+l*(u[h]+l*(r[h]+l*b));case 1:return u[h]+l*(2*r[h]+l*(3*b));case 2:return 2*r[h]+l*(6*b);default:return 6*b}})}function dt(o,i,e={}){let{method:t="fmm",ties:n="mean"}=e,s=L(o,i,t,n),u=q(s.x);u!==0&&(s=L(Array.from(o,c=>y(c,-u)),i,t,n));let r;if(e.xout!==void 0)r=Array.from(e.xout);else{let c=s.x.length,f=e.n??3*c;if(!Number.isFinite(f))throw new RangeError("'length.out' must be a finite number");if(!(f>0))throw new RangeError("'spline' requires n >= 1");r=D(e.xmin??y(s.x[0],u),e.xmax??y(s.x[c-1],u),f)}return{x:r,y:P(s,u===0?r:r.map(c=>y(c,-u)),0)}}function Nt(o,i,e={}){let{method:t="fmm",ties:n="mean"}=e;if(t==="monoH.FC"){let r=H(o,i,n);if(r.x.length===0)throw new RangeError("zero non-NA points");let c=q(r.x);c!==0&&(r=H(Array.from(o,a=>y(a,-c)),i,n));let f=wt(r.x,r.y);return(a,p=0)=>Y(r.x,r.y,f,c,c,a,p)}let s=L(o,i,t,n),u=q(s.x);return u===0?(r,c=0)=>P(s,r,c):(s=L(Array.from(o,r=>y(r,-u)),i,t,n),(r,c=0)=>{let f=B(c);return P(s,Array.from(r,a=>y(a,-u)),f).map(a=>y(a,-f*u))})}function wt(o,i){let e=o.length;if(e<2)throw new RangeError("length(m) must be at least two");let t=Array.from({length:e-1},(s,u)=>(i[u+1]-i[u])/(o[u+1]-o[u])),n=Array.from({length:e},(s,u)=>u===0?t[0]:u===e-1?t[e-2]:U(t[u-1],t[u]));for(let s=0;s<e-1;s++){let u=t[s];if(u===0){n[s]=0,n[s+1]=0;continue}let r=n[s]/u,c=n[s+1]/u,f=2*r+c-3,a=r+2*c-3;if(!(Number.isFinite(r*(f+a))&&Number.isFinite(f*f)&&Number.isFinite(r*r+c*c))&&Number.isFinite(n[s])&&Number.isFinite(n[s+1])&&Number.isFinite(u)){let g=M=>M===0?-1/0:Math.floor(Math.log2(Math.abs(M))),h=Math.max(g(n[s]),g(n[s+1]))-g(u),m=_([n[s]],[u],-h),d=_([n[s+1]],[u],-h),l=C(3,-h),b=2*m+d-l,N=m+2*d-l;if(b>0&&N>0&&m*(b+N)<b*b){let M=3*u/Math.sqrt(m*m+d*d);n[s]=M*m,n[s+1]=M*d}continue}if(f>0&&a>0&&r*(f+a)<f*f){let g=3*u/Math.sqrt(r*r+c*c);n[s]=g*r,n[s+1]=g*c}}return n}function Y(o,i,e,t,n,s,u){let r=B(u),c=o.length;return Array.from(s,f=>{if(Number.isNaN(f))return NaN;let a=t===0?f:y(f,-t),p=0,g=c;for(;p<g;){let w=p+g>>1;o[w]<=a?p=w+1:g=w}let h=p;if(h===0||h===c){let w=h===0?0:c-1;return r===0?i[w]+y(e[w]*(a-o[w]),t-n):r===1?y(e[w],-n):0}let m=o[h-1],d=o[h]-m,l=(a-m)/d,b=l-1,N=i[h-1],M=i[h],A=e[h-1],R=e[h],E=y(W(N,M,d),n-t);switch(r){case 0:{let w=l*l*(3-2*l),F=(k,v)=>{let z=y(d*k,t-n)*v;return Number.isFinite(z)||!Number.isFinite(k)||!Number.isFinite(v)?z:_([d,k,v],[],t-n)};return N*(1-w)+F(A,l*b*b)+M*w+F(R,l*l*b)}case 1:{if(Number.isFinite(E)||!Number.isFinite(N)||!Number.isFinite(M))return y(E*(-6*l*b)+A*(b*(3*l-1))+R*(l*(3*l-2)),-n);let w=M-N;return(Number.isFinite(w)?_([w,-6*l*b],[d],-t):_([M/2-N/2,-6*l*b],[d],1-t))+y(A*(b*(3*l-1))+R*(l*(3*l-2)),-n)}case 2:{if(Number.isFinite(E)||!Number.isFinite(N)||!Number.isFinite(M))return y((E*(6-12*l)+A*(6*l-4)+R*(6*l-2))/d,-n-t);let w=M-N;return(Number.isFinite(w)?_([w,6-12*l],[d,d],-2*t):_([M/2-N/2,6-12*l],[d,d],1-2*t))+y((A*(6*l-4)+R*(6*l-2))/d,-n-t)}default:{let w=-12*E+6*A+6*R,F=d*d;return F>=2**-1022&&F<1/0?y(w/F,-n-2*t):y(w/d/d,-n-2*t)}}})}function Mt(o,i,e){let t=o.length;if(i.length!==t||e.length!==t)throw new RangeError("'x', 'y' and 'm' must have the same length");let n=Array.from({length:t},(a,p)=>p).sort((a,p)=>o[a]-o[p]),s=n.map(a=>o[a]),u=n.map(a=>i[a]),r=n.map(a=>e[a]);for(let a=1;a<t;a++)if(!(s[a]-s[a-1]>0))throw new RangeError("'x' must be *strictly* increasing (non - NA)");let c=q(s),f=c===0?s:s.map(a=>y(a,-c));return(a,p=0)=>Y(f,u,r,c,0,a,p)}function yt(o,i,e){let t=Array.from(o),n=Array.from(i),s=t.length;if(n.length!==s)throw new RangeError("'xi' and 'yi' must have the same length");let u=Array.from(e),r=O(t),c=$(t);if(u.some(b=>b<r||b>c))throw new RangeError("Some interpolation points outside the nodes.");let f=Number.isFinite(r)&&Number.isFinite(c)&&!Number.isFinite(c-r),a=f?t.map(b=>b/2):t,p=a.map((b,N)=>{let M=1,A=0;for(let R=0;R<s;R++){if(R===N)continue;let E=b-a[R],w=M*E;if(M!==0&&E!==0&&Number.isFinite(E)&&!(Math.abs(w)>=2**-1022&&Math.abs(w)<1/0)){let k=Math.floor(Math.log2(Math.abs(M))),v=Math.floor(Math.log2(Math.abs(E)));M=y(M,-k)*y(E,-v),A+=k+v;continue}M=w;let F=Math.abs(M);if(F>2**500||F<2**-500&&F>0){let k=Math.floor(Math.log2(F));M=y(M,-k),A+=k}}return{p:M,e:A}}),g=p.reduce((b,N)=>Math.max(b,-N.e),-1/0),h=p.map(b=>y(1/b.p,-b.e-g)),m=t.every(Number.isFinite)&&n.every(Number.isFinite),d=m?n.reduce((b,N)=>N===0?b:Math.max(b,Math.floor(Math.log2(Math.abs(N)))),-1/0):0,l=b=>{if(d===-1/0)return 0;let N=1,M=0,A=[];for(let F=0;F<s;F++){let k=b-a[F];if(k===0)return;let v=Math.floor(Math.log2(Math.abs(k))),z=y(k,-v);N*=z;let x=Math.floor(Math.log2(Math.abs(N)));N=y(N,-x),M+=v+x;let I=1/p[F].p/z;if(!Number.isFinite(I)||I===0)return;let S=Math.floor(Math.log2(Math.abs(I)));A.push({r:y(I,-S),x:S-p[F].e-v})}let R=A.reduce((F,k)=>Math.max(F,k.x),-1/0),E=0;for(let F=0;F<s;F++)E+=y(A[F].r,A[F].x-R)*y(n[F],-d);if(E===0)return 0;let w=Math.floor(Math.log2(Math.abs(E)));return C(N*y(E,-w),M+R+d+w)};return u.map(b=>{let N=0,M=0,A=t.lastIndexOf(b);if(A>=0)return n[A];let R=0,E=0;for(let x=0;x<s;x++){let I=(f?b/2:b)-a[x],S=h[x]/I;N+=S*n[x],M+=S,R+=Math.abs(S),E+=Math.abs(S*n[x])}let w=N/M;if(m&&Number.isFinite(R)&&R>0&&Math.abs(M)<y(R,-100)&&Number.isFinite(E)&&Math.abs(N)>=y(E,-26)){let x=l(f?b/2:b);if(x!==void 0)return x}if(Number.isFinite(w)||!m)return w;let F=p.map((x,I)=>{let S=(f?b/2:b)-a[I],K=Math.floor(Math.log2(Math.abs(S)));return{r:1/x.p/y(S,-K),x:-x.e-K}});if(!F.every(x=>Number.isFinite(x.r)&&Number.isFinite(x.x)))return w;let k=F.reduce((x,I)=>Math.max(x,I.x),-1/0),v=0,z=0;for(let x=0;x<s;x++){let I=y(F[x].r,F[x].x-k);v+=I*n[x],z+=I}return v/z})}function Ft(o,i,e,t){let n=Array.from(o),s=Array.from(i),u=Array.from(e),r=n.length;if(s.length!==r||u.length!==r)throw new RangeError("'xi', 'yi' and 'di' must have the same length");let c=q([...n].sort((h,m)=>h-m)),f=c===0?Z(n,s,u):void 0;if(f?.lost&&[n,s,u].every(h=>h.every(Number.isFinite))){let h=Math.floor(Math.log2($(n.map(Math.abs))));h!==0&&([c,f]=[h,void 0])}f===void 0&&(f=Z(n.map(h=>y(h,-c)),s,u.map(h=>y(h,c))));let{z:a,coef:p}=f,g=2*r;return Array.from(t,h=>{let m=p[g-1],d=c===0?h:y(h,-c);for(let l=g-2;l>=0;l--)m=m*(d-a[l])+p[l];return m})}function Z(o,i,e){let t=o.flatMap(f=>[f,f]),n=t.length,s=!1,u=i.flatMap(f=>[f,f]),r=[u[0]],c=u.slice();for(let f=1;f<n;f++){let a=[];for(let p=0;p<n-f;p++)if(f===1&&t[p+1]===t[p])a.push(e[p>>1]);else{let g=c[p+1]-c[p],h=t[p+f]-t[p],m=W(c[p],c[p+1],h);Number.isFinite(c[p+1])&&Number.isFinite(c[p])&&g!==0&&h!==0&&!(Math.abs(m)>=2**-1022&&Math.abs(m)<1/0)&&(s=!0),a.push(m)}r.push(a[0]),c=a}return{z:t,coef:r,lost:s}}function At(o,i,e,t=[],n={}){let s=n.method??"rk4";if(s!=="euler"&&s!=="rk2"&&s!=="rk4")throw new RangeError(`unknown method '${String(s)}'`);if(!i.every(Number.isFinite))throw new RangeError("'times' must be finite values");let u=[...t],r=o.length,c=(g,h)=>{let m=Array.from(e(g,h,u));if(m.length!==r)throw new RangeError(`The number of derivatives returned by func() (${m.length}) must equal the length of the initial conditions vector (${r})`);return m},f=(g,h,m)=>g.map((d,l)=>d+h*m[l]),a=[...o],p=[];if(i.length===0)return p;p.push([i[0],...a]);for(let g=1;g<i.length;g++){let h=i[g-1],m=i[g]-h;if(!Number.isFinite(m)&&Number.isFinite(h)&&Number.isFinite(i[g])){a=Rt(a,h,i[g]/2-h/2,s,c),p.push([i[g],...a]);continue}let d=c(h,a);if(s==="euler")a=f(a,m,d);else if(s==="rk2"){let l=c(h+m,f(a,m,d));a=a.map((b,N)=>b+m*(.5*d[N]+.5*l[N]))}else{let l=c(h+m/2,f(a,m/2,d)),b=c(h+m/2,f(a,m/2,l)),N=c(h+m,f(a,m,b)),M=m/6,A=m===0||Math.abs(M)>=2**-1022,R=Math.abs(m)<1?2**60:1;a=a.map((E,w)=>{let F=M*(d[w]+2*l[w]+2*b[w]+N[w]);if(A&&Number.isFinite(F))return E+F;let k=d[w]/4+l[w]/2+b[w]/2+N[w]/4,v=m*R*k;if(!Number.isFinite(k)&&[d[w],l[w],b[w],N[w]].every(Number.isFinite)){let x=d[w]/8+l[w]/4+b[w]/4+N[w]/8;return E+2*(m*x/1.5)}if(Number.isFinite(v)||!Number.isFinite(k))return E+v/1.5/R;let z=m*k;return E+(Number.isFinite(z)?z/1.5:2*(m/2*k/1.5))})}p.push([i[g],...a])}return p}function Rt(o,i,e,t,n){let s=(g,h,m)=>g.map((d,l)=>d+h*m[l]+h*m[l]),u=i+e,r=u+e,c=n(i,o);if(t==="euler")return s(o,e,c);if(t==="rk2"){let g=n(r,s(o,e,c));return s(o,e,c.map((h,m)=>.5*h+.5*g[m]))}let f=n(u,o.map((g,h)=>g+e*c[h])),a=n(u,o.map((g,h)=>g+e*f[h])),p=n(r,s(o,e,a));return s(o,e/1.5,c.map((g,h)=>g/4+f[h]/2+a[h]/2+p[h]/4))}function tt(o){if(!(Number.isFinite(o)&&o!==0))throw new RangeError("'eps' must be a finite nonzero number")}function nt(o){let i=o.eps??1e-4;return tt(i),i}function G(o,i,e){let t=i.eps??1e-4,n=i.d??e,s=i.zeroTol??Math.sqrt(Number.EPSILON/7e-7);if(!(Number.isFinite(n)&&n!==0))throw new RangeError("'d' must be a finite nonzero number");if(tt(t),!(Number.isFinite(s)&&s>=0))throw new RangeError("'zeroTol' must be a non-negative finite number");let u=i.r??4;if(!(Number.isInteger(u)&&u>=1))throw new RangeError("'r' must be a positive integer");if(u>512)throw new RangeError("'r' must be at most 512");let r=o.map(c=>Math.abs(n*c)+(Math.abs(c)<s?t:0));return r.forEach((c,f)=>{if(!(Math.abs(c)>0&&Math.abs(c)<1/0))throw new RangeError(`the step for x[${f}] is ${c}: not a nonzero finite number`)}),{eps:t,r:u,h0:r}}function T(o){let i=[...o];for(let e=1;e<i.length;e++){let t=4**e;for(let n=0;n<i.length-e;n++)i[n]=(i[n+1]*t-i[n])/(t-1)}return i[0]}function j(o,i,e){let t=[...o];return t[i]=t[i]+e,t}function et(o){let i=o.method??"Richardson";if(i!=="Richardson"&&i!=="simple")throw new RangeError(`unknown method "${String(i)}" (expected "Richardson" or "simple")`);return i}function Et(o,i,e={}){let t=[...i],n=t.length;if(et(e)==="simple"){let c=nt(e),f=o([...t]);return t.map((a,p)=>(o(j(t,p,c))-f)/c)}let{r:s,h0:u}=G(t,e,1e-4),r=[];for(let c=0;c<n;c++){let f=[],a=u[c];for(let p=0;p<s;p++){if(p>0&&Math.abs(f[p-1])<1e-20?f.push(0):f.push((o(j(t,c,a))-o(j(t,c,-a)))/(2*a)),Number.isNaN(f[p]))throw new RangeError(`func returned NaN at step ${a} from x`);a/=2}r.push(T(f))}return r}function xt(o,i,e={}){let t=[...i],n=t.length,s=Array.from(o([...t])),u=s.map(()=>new Array(n).fill(NaN)),r=a=>{let p=o(a);if(p.length!==s.length)throw new RangeError(`jacobian: func returned ${p.length} values at a shifted x, but ${s.length} at x`);return p};if(et(e)==="simple"){let a=nt(e);for(let p=0;p<n;p++){let g=r(j(t,p,a));s.forEach((h,m)=>u[m][p]=(g[m]-h)/a)}return u}let{r:c,h0:f}=G(t,e,1e-4);for(let a=0;a<n;a++){let p=s.map(()=>[]),g=f[a];for(let h=0;h<c;h++){let m=r(j(t,a,g)),d=r(j(t,a,-g));s.forEach((l,b)=>p[b].push((m[b]-d[b])/(2*g))),g/=2}s.forEach((h,m)=>u[m][a]=T(p[m]))}return u}function kt(o,i,e={}){if((e.method??"Richardson")!=="Richardson")throw new RangeError('hessian supports only method "Richardson"');let t=[...i],n=t.length,{r:s,h0:u}=G(t,e,.1),r=o([...t]),c=[];for(let a=0;a<n;a++){let p=[],g=u[a];for(let h=0;h<s;h++){let m=o(j(t,a,g)),d=o(j(t,a,-g)),l=m-2*r+d,b=g**2;!Number.isFinite(l)&&Number.isFinite(m)&&Number.isFinite(d)&&Number.isFinite(r)?p.push((m/g-2*(r/g)+d/g)/g):p.push(Number.isFinite(b)?l/b:l/g/g),g/=2}c.push(T(p))}let f=t.map(()=>new Array(n).fill(NaN));for(let a=0;a<n;a++){f[a][a]=c[a];for(let p=0;p<a;p++){let g=[],h=u[a],m=u[p];for(let d=0;d<s;d++){let l=j(j(t,a,h),p,m),b=j(j(t,a,-h),p,-m),N=o(l),M=o(b),A=N-2*r+M,R=2*h*m;!Number.isFinite(A)&&Number.isFinite(N)&&Number.isFinite(M)&&Number.isFinite(r)?g.push((N/h/m-2*(r/h/m)+M/h/m-c[a]*(h/m)-c[p]*(m/h))/2):Number.isFinite(R)&&Number.isFinite(h**2)&&Number.isFinite(m**2)?g.push((A-c[a]*h**2-c[p]*m**2)/R):g.push((A/h/m-c[a]*(h/m)-c[p]*(m/h))/2),h/=2,m/=2}f[a][p]=f[p][a]=T(g)}}return f}export{ht as approx,yt as barylag,Et as grad,Ft as hermiteInterp,kt as hessian,rt as integrate,xt as jacobian,At as ode,at as optim,it as optimHess,ot as optimize,dt as spline,Nt as splinefun,Mt as splinefunH,st as uniroot};
@@ -61,6 +61,10 @@ export function localMin(f, lower, upper, tol = LOCALMIN_TOL) {
61
61
  }
62
62
  // f must not be evaluated too close to x
63
63
  const u = Math.abs(d) >= tol1 ? x + d : d >= 0 ? x + tol1 : x - tol1; // x + sign(tol1, d)
64
+ // a step that rounds to 0 (tol1 = 0 among the subnormals, for a tol whose third underflows: the bracket stayed
65
+ // [5e-324, 1e-323] for x² on [-1, 1] at tol 5e-324, where R does not return either) cannot narrow the bracket
66
+ if (u === x)
67
+ break;
64
68
  const fu = f(u);
65
69
  evaluations++;
66
70
  // update a, b, v, w and x
@@ -95,7 +95,9 @@ export interface OptimResult {
95
95
  export declare function optimHess(par: readonly number[], fn: (par: number[]) => number, gr?: (par: number[]) => number[], control?: OptimControl): number[][];
96
96
  /**
97
97
  * General-purpose minimisation of `fn` from the starting point `par`. Equivalent to R's `optim()`. The same methods
98
- * with the same iterations, so the same results and counts.
98
+ * with the same iterations, so the same results and counts, except CG: after an accepted step it tries the minimum of
99
+ * the parabola through the start and the accepted point, where R's cgmin always tries the midpoint (so CG's path,
100
+ * results and counts differ from R's).
99
101
  *
100
102
  * @example
101
103
  * ```ts
@@ -5,6 +5,7 @@
5
5
  // theorems for a class of simulated annealing algorithms on R^d", J. Appl. Probab. 29 (1992) 885-895) with R's random
6
6
  // numbers; Brent is optimize(). Written for rStats.js from the specification (no R code was read or used).
7
7
  import { optimize } from "../numerics/integrate.js";
8
+ import { ldexp, ldexpWide } from "../internal/summary.js";
8
9
  import { normRand, unifRand } from "../random/rng.js";
9
10
  import { lbfgsb } from "./lbfgsb.js";
10
11
  // R's constants (oracle/optim-behaviour.md, rule 5)
@@ -28,6 +29,16 @@ function recycle(v, n, dflt) {
28
29
  throw new RangeError("argument of length 0");
29
30
  return Array.from({ length: n }, (_, i) => a[i % a.length]);
30
31
  }
32
+ /**
33
+ * R's check in fminfn and (with an analytic gradient) fmingr: every point at which fn or gr is evaluated must be
34
+ * finite. An infinite start trapped Nelder-Mead's simplex set-up, and an infinite gradient BFGS's and CG's line
35
+ * search, in loops that never ended (#354)
36
+ */
37
+ function finitePar(p) {
38
+ for (const v of p)
39
+ if (!Number.isFinite(v))
40
+ throw new Error("non-finite value supplied by optim");
41
+ }
31
42
  /** The scaled problem: p = par / parscale, f(p) = fn(p * parscale) / fnscale */
32
43
  class Scaled {
33
44
  fn;
@@ -42,22 +53,39 @@ class Scaled {
42
53
  this.parscale = parscale;
43
54
  this.fnscale = fnscale;
44
55
  this.ndeps = ndeps;
56
+ // fn / +-Infinity is 0 or NaN everywhere: R returns the start with value NaN and convergence 0 (#248); NaN and 0
57
+ // fail at the initial value, as in R
58
+ if (fnscale === Infinity || fnscale === -Infinity)
59
+ throw new RangeError("'fnscale' must not be infinite");
45
60
  this.n = parscale.length;
46
61
  }
47
62
  unscale(p) {
48
63
  return p.map((v, i) => v * this.parscale[i]);
49
64
  }
50
65
  f(p) {
66
+ finitePar(p);
51
67
  return this.fn(this.unscale(p)) / this.fnscale;
52
68
  }
53
69
  /** Gradient in the scaled parameters; numerical steps are cut at the bounds when given (L-BFGS-B) */
54
70
  g(p, lower, upper) {
55
71
  const { n, parscale, fnscale } = this;
56
72
  if (this.gr !== undefined) {
73
+ finitePar(p);
57
74
  const gx = this.gr(this.unscale(p));
58
75
  if (gx.length !== n)
59
76
  throw new RangeError(`gradient in optim evaluated to length ${gx.length} not ${n}`);
60
- return gx.map((v, i) => (v * parscale[i]) / fnscale);
77
+ // as the numerical gradient's check: R does not check gr, and a NaN component returned the start as converged
78
+ // (convergence 0) without a step (#355)
79
+ for (let i = 0; i < n; i++) {
80
+ if (!Number.isFinite(gx[i]))
81
+ throw new Error(`non-finite value of the gradient [${i + 1}] supplied by 'gr'`);
82
+ }
83
+ // v·parscale can overflow where the scaled gradient is finite (1e200 · 1e200 / 1e300): only there divide by
84
+ // fnscale first (R's fmingr overflows to NaN; #498)
85
+ return gx.map((v, i) => {
86
+ const w = v * parscale[i];
87
+ return Number.isFinite(w) ? w / fnscale : (v / fnscale) * parscale[i];
88
+ });
61
89
  }
62
90
  const x = this.unscale(p);
63
91
  const slopes = new Array(n);
@@ -403,6 +431,7 @@ function conjugateGradients(s, start, type, abstol, reltol, maxit) {
403
431
  dir[i] = dir[i] * beta - grad[i];
404
432
  slope += dir[i] * grad[i];
405
433
  }
434
+ const atStart = best;
406
435
  const search = backtrack(s, from, dir, slope, best, firstStep, point, value);
407
436
  fnEvals += search.evals;
408
437
  value = search.value;
@@ -410,8 +439,10 @@ function conjugateGradients(s, start, type, abstol, reltol, maxit) {
410
439
  const step = search.step;
411
440
  if (moved) {
412
441
  best = value;
413
- // minimum of the parabola through the start (value and slope) and the accepted point
414
- let curvature = 2 * (value - best - slope * step);
442
+ // minimum of the parabola through the start (value and slope) and the accepted point. (R's cgmin forms it after
443
+ // setting the start's value to the accepted one, so the curvature is -2 slope step and the trial point always
444
+ // the midpoint; issue #15)
445
+ let curvature = 2 * (value - atStart - slope * step);
415
446
  if (curvature > 0) {
416
447
  curvature = -((slope * step * step) / curvature);
417
448
  for (let i = 0; i < n; i++)
@@ -490,8 +521,14 @@ function hessianOf(s, par) {
490
521
  p[i] = centre - step;
491
522
  const gradDown = s.g(p);
492
523
  p[i] = centre;
493
- for (let j = 0; j < n; j++)
494
- hess[i][j] = (fnscale * (gradUp[j] - gradDown[j])) / (2 * step * parscale[i] * parscale[j]);
524
+ for (let j = 0; j < n; j++) {
525
+ const num = fnscale * (gradUp[j] - gradDown[j]);
526
+ const den = 2 * step * parscale[i] * parscale[j];
527
+ const q = num / den;
528
+ // the difference or the product can overflow (or the product underflow) where the quotient is representable:
529
+ // only there form it from factors scaled by powers of 2 (R's optimhess overflows to 0 or Inf; #503)
530
+ hess[i][j] = Number.isFinite(num) && Number.isFinite(den) && Number.isFinite(q) ? q : scaledQuotient(fnscale, gradUp[j], gradDown[j], step, parscale[i], parscale[j], q);
531
+ }
495
532
  }
496
533
  // symmetrise
497
534
  for (let i = 0; i < n; i++) {
@@ -503,10 +540,25 @@ function hessianOf(s, par) {
503
540
  }
504
541
  return hess;
505
542
  }
543
+ /**
544
+ * fnscale (up - down) / (2 step ps_i ps_j) with each factor scaled to [1, 2) by a power of 2 and the exponents added
545
+ * back at the end, so that no intermediate overflows or underflows. `direct` (the quotient as written) is kept when a
546
+ * factor is 0 or not finite
547
+ */
548
+ function scaledQuotient(fnscale, up, down, step, pi, pj, direct) {
549
+ const f = [up / 2 - down / 2, fnscale, step, pi, pj];
550
+ if (f.some((v) => v === 0 || !Number.isFinite(v)))
551
+ return direct;
552
+ const e = f.map((v) => Math.floor(Math.log2(Math.abs(v))));
553
+ const m = f.map((v, k) => ldexp(v, -e[k]));
554
+ return ldexpWide((m[0] * m[1]) / (m[2] * m[3] * m[4]), e[0] + e[1] - e[2] - e[3] - e[4]);
555
+ }
506
556
  const METHODS = ["Nelder-Mead", "BFGS", "CG", "L-BFGS-B", "SANN", "Brent"];
507
557
  /**
508
558
  * General-purpose minimisation of `fn` from the starting point `par`. Equivalent to R's `optim()`. The same methods
509
- * with the same iterations, so the same results and counts.
559
+ * with the same iterations, so the same results and counts, except CG: after an accepted step it tries the minimum of
560
+ * the parabola through the start and the accepted point, where R's cgmin always tries the midpoint (so CG's path,
561
+ * results and counts differ from R's).
510
562
  *
511
563
  * @example
512
564
  * ```ts
@@ -533,9 +585,17 @@ export function optim(par, fn, options = {}) {
533
585
  const parscale = recycle(control.parscale, n, 1);
534
586
  const fnscale = control.fnscale ?? 1;
535
587
  const ndeps = recycle(control.ndeps, n, 1e-3);
536
- const maxit = control.maxit ?? (method === "Nelder-Mead" ? 500 : method === "SANN" ? 10000 : 100);
588
+ const maxit0 = control.maxit ?? (method === "Nelder-Mead" ? 500 : method === "SANN" ? 10000 : 100);
589
+ // R's as.integer: truncated, and an error beyond the integer range (Infinity kept SANN's loop running forever)
590
+ if (!(Math.abs(maxit0) <= 2147483647))
591
+ throw new RangeError("'maxit' is not an integer");
592
+ const maxit = Math.trunc(maxit0);
537
593
  const reltol = control.reltol ?? Math.sqrt(2 ** -52);
538
594
  const abstol = control.abstol ?? -Infinity;
595
+ if (!(reltol >= 0 && reltol < Infinity))
596
+ throw new RangeError("'reltol' must be a non-negative finite number");
597
+ if (Number.isNaN(abstol))
598
+ throw new RangeError("'abstol' must not be NaN");
539
599
  if (method === "Nelder-Mead" && n === 1)
540
600
  warnings.push('one-dimensional optimization by Nelder-Mead is unreliable:\nuse "Brent" or optimize() directly');
541
601
  if (method === "L-BFGS-B" && (control.reltol !== undefined || control.abstol !== undefined))
@@ -558,6 +618,11 @@ export function optim(par, fn, options = {}) {
558
618
  const perTemperature = control.tmax ?? 10;
559
619
  if (!(perTemperature >= 1))
560
620
  throw new RangeError("'tmax' is not a positive integer");
621
+ // (R fails on 0 with "non-finite value supplied by optim" and accepts a negative one, where the acceptance
622
+ // probability exp(-Δ / T) prefers uphill moves; here 0 returned the start silently)
623
+ if (!(control.temp === undefined || (control.temp > 0 && control.temp < Infinity))) {
624
+ throw new RangeError("'temp' must be a positive finite number");
625
+ }
561
626
  run = annealing(s, start, maxit, Math.trunc(perTemperature), control.temp ?? 10);
562
627
  break;
563
628
  }
@@ -578,6 +643,13 @@ export function optim(par, fn, options = {}) {
578
643
  // L-BFGS-B
579
644
  const lo = lower.map((v, i) => v / parscale[i]);
580
645
  const up = upper.map((v, i) => v / parscale[i]);
646
+ // R's as.integer: truncated (1.5 indexed the workspace with fractions, 0.5 ran with m = 0.5); NaN and values
647
+ // beyond the integer range are NA (the latter with R's warning), which lbfgsb rejects as M .LE. 0, like any
648
+ // m <= 0 (passed as 0: a negative m gave negative workspace lengths) (#362)
649
+ const lmm0 = control.lmm ?? 5;
650
+ if (Math.abs(lmm0) > 2147483647)
651
+ warnings.push("NAs introduced by coercion to integer range");
652
+ const lmm = Math.abs(lmm0) <= 2147483647 ? Math.max(Math.trunc(lmm0), 0) : 0;
581
653
  if (n === 0) {
582
654
  run = { par: [], value: s.f([]), fnEvals: 0, gradEvals: 0, code: 0 };
583
655
  message = "NOTHING TO DO";
@@ -589,7 +661,7 @@ export function optim(par, fn, options = {}) {
589
661
  return fl && fu ? 2 : fl ? 1 : fu ? 3 : 0;
590
662
  });
591
663
  let iterations = 0;
592
- const r = lbfgsb(n, control.lmm ?? 5, start, lo, up, nbd, control.factr ?? 1e7, control.pgtol ?? 0, (x) => {
664
+ const r = lbfgsb(n, lmm, start, lo, up, nbd, control.factr ?? 1e7, control.pgtol ?? 0, (x) => {
593
665
  const f = s.f(x);
594
666
  if (!Number.isFinite(f))
595
667
  throw new Error("L-BFGS-B needs finite values of 'fn'");
@@ -6,7 +6,8 @@
6
6
  // 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 { rchisq } from "./gamma.js";
9
+ import { rchisq, rgamma1 } from "./gamma.js";
10
+ import { rpois1 } from "./poisson.js";
10
11
  /** The value of log(DBL_MAX) (1024 log 2) */
11
12
  const EXPMAX = 1024 * Math.LN2;
12
13
  let beta = 0, gamma = 0, delta = 0, k1 = 0, k2 = 0;
@@ -81,6 +82,22 @@ export function rbeta1(aa, bb) {
81
82
  beta = Math.sqrt((alpha - 2) / (2 * a * b - alpha));
82
83
  gamma = a + 1 / beta;
83
84
  }
85
+ if (!(2 * a * b < Infinity)) {
86
+ // 2ab overflows: the constants above are 0, Infinity or NaN. The larger shape B is then above 1e154 / min, and
87
+ // G_B / B = 1 + O(B^-1/2) to far below double precision, so X = G_m / (G_m + B) for the smaller shape m. With m up
88
+ // to 1e32 G_m is drawn (rbeta(5, 1.1, 1e308) gave 1.1e-308 five times, the mean, as R; issue #30: the draws differ
89
+ // from R's there). Beyond, both are so large that the mean is the draw to double precision (a relative standard
90
+ // deviation below 1e-16); the two uniforms of R's single pass are drawn, so the stream stays R's
91
+ const m = Math.min(aa, bb);
92
+ if (m <= 1e32) {
93
+ const big = Math.max(aa, bb);
94
+ const r = rgamma1(m, 1) / big;
95
+ return aa <= bb ? r / (1 + r) : 1 / (1 + r);
96
+ }
97
+ unifRand();
98
+ unifRand();
99
+ return aa >= bb ? 1 / (1 + bb / aa) : aa / bb / (1 + aa / bb);
100
+ }
84
101
  let r, t;
85
102
  do {
86
103
  const u1 = unifRand();
@@ -97,6 +114,19 @@ export function rbeta1(aa, bb) {
97
114
  } while (r + alpha * Math.log(alpha / (b + w)) < t);
98
115
  return aa !== a ? b / (b + w) : w / (b + w);
99
116
  }
117
+ /** Half a noncentral chi-squared variate with 2 shape degrees of freedom (the draws of rnchisq1(2 shape, ncp)) */
118
+ function halfNoncentralChisq(shape, ncp) {
119
+ if (!Number.isFinite(ncp) || ncp < 0)
120
+ return NaN;
121
+ if (ncp === 0)
122
+ return shape === 0 ? 0 : rgamma1(shape, 1);
123
+ let r = rpois1(ncp / 2);
124
+ if (r > 0)
125
+ r = rgamma1(r, 1);
126
+ if (shape > 0)
127
+ r += rgamma1(shape, 1);
128
+ return r;
129
+ }
100
130
  /**
101
131
  * Random numbers from the beta distribution. Equivalent to R's `rbeta()`.
102
132
  *
@@ -119,7 +149,26 @@ export function rbeta(n, shape1, shape2, options = {}) {
119
149
  if (ncp === undefined)
120
150
  return generate(n, () => rbeta1(shape1, shape2));
121
151
  // Noncentral beta: as in R, generate n draws X ~ noncentral χ²(2 shape1, ncp), then n draws Y ~ χ²(2 shape2), and return X / (X + Y)
122
- const x = rchisq(n, 2 * shape1, { ncp });
123
- const y = rchisq(n, 2 * shape2);
124
- return x.map((xi, i) => xi / (xi + y[i]));
152
+ let x;
153
+ let y;
154
+ if (Number.isFinite(shape1) && Number.isFinite(shape2) && (!Number.isFinite(2 * shape1) || !Number.isFinite(2 * shape2))) {
155
+ // 2 shape overflows (rbeta(3, 1e308, 1e308, ncp = 0) was NaN, R too): X / 2 and Y / 2 as gamma variates, with the
156
+ // draws of R's rnchisq (rpois(ncp / 2) and a gamma for the Poisson count, then the gamma for the shape)
157
+ x = generate(n, () => halfNoncentralChisq(shape1, ncp));
158
+ y = generate(n, () => rgamma1(shape2, 1));
159
+ }
160
+ else {
161
+ x = rchisq(n, 2 * shape1, { ncp });
162
+ y = rchisq(n, 2 * shape2);
163
+ }
164
+ // With both shapes 0, X = Y = 0 (always for ncp = 0, for a Poisson count 0 otherwise) is the Beta(0, 0) component of
165
+ // the mixture: 0 or 1 with probability 1/2 each, decided by a uniform as the central rbeta does (R returns 0 / 0 =
166
+ // NaN without a draw, so the stream differs from R's only there)
167
+ return x.map((xi, i) => {
168
+ if (xi === 0 && y[i] === 0 && shape1 === 0 && shape2 === 0)
169
+ return unifRand() < 0.5 ? 0 : 1;
170
+ const yi = y[i];
171
+ // (the sum of two variates near 1e308 overflows: halved first)
172
+ return Number.isFinite(xi + yi) || !Number.isFinite(xi) || !Number.isFinite(yi) ? xi / (xi + yi) : xi / 2 / (xi / 2 + yi / 2);
173
+ });
125
174
  }
@@ -1,8 +1,19 @@
1
+ /**
2
+ * log(f(ix) / f(m)) for the binomial probabilities f with n trials and success probability p = 1 - q, m the integer
3
+ * mode, by Stirling's formula (the final test of BTPE). The corrections of log m! and log (n - m)! enter with a plus
4
+ * 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
5
+ * 0.02 in the log near n p = 30), which changes some acceptances and so the stream from R's
6
+ */
7
+ export declare function btpeLogRatio(n: number, p: number, q: number, m: number, ix: number): number;
1
8
  /** One binomial variate (nin trials, success probability pp) */
2
9
  export declare function rbinom1(nin: number, pp: number): number;
3
10
  /**
4
11
  * Random numbers from the binomial distribution. Equivalent to R's `rbinom()`.
5
12
  *
13
+ * For `size * min(prob, 1 - prob) >= 30` (algorithm BTPE) the stream can depart from R's: R's final acceptance test has
14
+ * two Stirling corrections with the wrong sign, and here the signs are right (`setSeed(439); rbinom(1, 10000, 0.5)` is
15
+ * 4879, R 5023). Below 30 (inversion) the stream is R's.
16
+ *
6
17
  * @param n Number of values to generate (fractions are truncated, as in R).
7
18
  * @param size Number of trials.
8
19
  * @param prob Probability of success in each trial.
@@ -24,10 +35,10 @@ export declare function rbinom(n: number, size: number, prob: number): number[];
24
35
  * with one draw per row (the transpose of R's result). The random stream is the same as R's.
25
36
  *
26
37
  * @param n Number of values to generate (fractions are truncated, as in R).
27
- * @param size Number of objects distributed into the K categories in each draw.
38
+ * @param size Number of objects distributed into the K categories in each draw (fractions are truncated, as in R).
28
39
  * @param prob Category weights of length K. They need not sum to 1 (they are divided by their sum).
29
- * @returns An array of `n` arrays, each of length K and summing to `size`.
30
- * @throws RangeError if `size` is not a non-negative integer, or `prob` has a negative or
40
+ * @returns An array of `n` arrays, each of length K and summing to the truncated `size`.
41
+ * @throws RangeError if the truncated `size` is negative or 2^31 or more, or `prob` has a negative or
31
42
  * non-finite value, or no positive value.
32
43
  *
33
44
  * @example
@@ -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,8 @@
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";
7
9
  /**
8
10
  * Random numbers from the uniform distribution. Equivalent to R's `runif()`.
9
11
  *
@@ -29,7 +31,8 @@ export function runif(n, options = {}) {
29
31
  if (min === max)
30
32
  return min;
31
33
  const u = unifRand();
32
- return min + (max - min) * u;
34
+ // a width that overflows (R returns Inf): the weighted mean of the ends instead
35
+ return Number.isFinite(max - min) ? min + (max - min) * u : min * (1 - u) + max * u;
33
36
  });
34
37
  }
35
38
  export function rnorm1(mean, sd) {
@@ -37,7 +40,11 @@ export function rnorm1(mean, sd) {
37
40
  return NaN;
38
41
  if (sd === 0 || !Number.isFinite(mean))
39
42
  return mean;
40
- return mean + sd * normRand();
43
+ const z = normRand();
44
+ const x = mean + sd * z;
45
+ // sd·Z can overflow although mean + sd·Z is in range (R gives ±Inf): the same sum halved (exact for such a large sd
46
+ // and a mean that matters), rounded once and doubled
47
+ return Number.isFinite(x) ? x : 2 * (mean / 2 + (sd / 2) * z);
41
48
  }
42
49
  /**
43
50
  * Random numbers from the normal distribution. Equivalent to R's `rnorm()`.
@@ -78,8 +85,13 @@ export function rnorm(n, options = {}) {
78
85
  * @category Random numbers
79
86
  */
80
87
  export function rexp(n, options = {}) {
81
- const scale = 1 / (options.rate ?? 1);
88
+ const rate = options.rate ?? 1;
89
+ const scale = 1 / rate;
82
90
  return generate(n, () => {
91
+ // a positive rate below about 5.6e-309 has 1 / rate = Infinity: the variate itself (R gives NaN), which overflows
92
+ // unless the exponential variate is small
93
+ if (scale === Infinity && rate > 0)
94
+ return expRand() / rate;
83
95
  if (!Number.isFinite(scale) || scale <= 0)
84
96
  return scale === 0 ? 0 : NaN;
85
97
  return scale * expRand();
@@ -130,6 +142,12 @@ export function rlogis(n, options = {}) {
130
142
  return generate(n, () => {
131
143
  if (Number.isNaN(location) || !Number.isFinite(scale))
132
144
  return NaN;
145
+ // a negative scale defines no distribution (dlogis, plogis and qlogis give NaN; R draws from it). The uniform R
146
+ // draws is drawn as well, so the stream stays R's
147
+ if (scale < 0) {
148
+ unifRand();
149
+ return NaN;
150
+ }
133
151
  if (scale === 0 || !Number.isFinite(location))
134
152
  return location;
135
153
  const u = unifRand();
@@ -181,9 +199,19 @@ export function rcauchy(n, options = {}) {
181
199
  export function rweibull(n, shape, options = {}) {
182
200
  const { scale = 1 } = options;
183
201
  return generate(n, () => {
184
- if (!Number.isFinite(shape) || !Number.isFinite(scale) || shape <= 0 || scale <= 0) {
202
+ // an invalid shape (or a negative scale) is NaN also with scale = 0 (R returns 0 there; no variate is drawn either
203
+ // way); scale = 0 is the point mass at 0
204
+ if (!(shape > 0) || !(scale >= 0))
205
+ return NaN;
206
+ if (!Number.isFinite(shape) || !Number.isFinite(scale) || scale === 0) {
185
207
  return scale === 0 ? 0 : NaN;
186
208
  }
187
- return scale * Math.pow(-Math.log(unifRand()), 1 / shape);
209
+ const e = -Math.log(unifRand());
210
+ const p = Math.pow(e, 1 / shape);
211
+ // for a small shape the power can overflow although the variate is in range for a small scale (R gives Inf): in
212
+ // logs then, double-double so that the large log keeps its digits
213
+ if (p !== Infinity)
214
+ return scale * p;
215
+ return ddExp(ddAdd(ddLog([scale, 0]), ddMulNum(ddLog([e, 0]), 1 / shape)))[0];
188
216
  });
189
217
  }