@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
@@ -13,9 +13,16 @@
13
13
  // (merging tied x values, extrapolation, the choice of the interval at a knot, defaults and error messages) follow
14
14
  // R's documented and observed behaviour.
15
15
  // Each spline piece is y + b h + c h^2 + d h^3 with h the distance from its left knot.
16
- import { mean } from "../internal/summary.js";
16
+ import { ldexp, ldexpWide, mean } from "../internal/summary.js";
17
17
  import { seqLength } from "../internal/seq.js";
18
+ import { optionalArgs } from "../internal/optionalArgs.js";
18
19
  import { findInterval } from "../descriptive/table.js";
20
+ import { maxOf, midpoint, minOf } from "../internal/extremes.js";
21
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
22
+ import { checkOptions } from "../internal/checkOptions.js";
23
+ const APPROX_KEYS = ["xout", "method", "n", "yleft", "yright", "rule", "f", "ties"];
24
+ const SPLINE_KEYS = ["n", "method", "xmin", "xmax", "xout", "ties"];
25
+ const SPLINEFUN_KEYS = ["method", "ties"];
19
26
  /**
20
27
  * The data as R uses it for interpolation: pairs with a NaN dropped, sorted by x, and each run of equal x merged into
21
28
  * one point whose y is `ties` of the run's y values (a single point keeps its y).
@@ -29,8 +36,8 @@ function regularize(x, y, ties = "mean") {
29
36
  idx.push(i);
30
37
  idx.sort((a, b) => x[a] - x[b]); // stable
31
38
  const merge = typeof ties === "function" ? ties
32
- : ties === "min" ? (v) => Math.min(...v)
33
- : ties === "max" ? (v) => Math.max(...v)
39
+ : ties === "min" ? (v) => minOf(v)
40
+ : ties === "max" ? (v) => maxOf(v)
34
41
  : mean;
35
42
  const xs = [];
36
43
  const ys = [];
@@ -47,14 +54,78 @@ function regularize(x, y, ties = "mean") {
47
54
  }
48
55
  /** Linear interpolation at v strictly inside [X[i], X[i+1]], grouped as y_i + (y_{i+1} - y_i) ((v - x_i) / h_i). */
49
56
  function linearAt(X, Y, i, v) {
50
- const t = (v - X[i]) / (X[i + 1] - X[i]);
51
- return Y[i] + (Y[i + 1] - Y[i]) * t;
57
+ let t = (v - X[i]) / (X[i + 1] - X[i]);
58
+ // differences of finite values that overflow are taken in half coordinates (approx(c(-1e308, 1e308), c(0, 1),
59
+ // xout = 0) was 0, and approx(c(0, 1), c(-1e308, 1e308), xout = 0.5) Infinity; R too)
60
+ if (!Number.isFinite(X[i + 1] - X[i]) || !Number.isFinite(v - X[i]))
61
+ t = (v / 2 - X[i] / 2) / (X[i + 1] / 2 - X[i] / 2);
62
+ const dy = Y[i + 1] - Y[i];
63
+ if (!Number.isFinite(dy) && Number.isFinite(Y[i]) && Number.isFinite(Y[i + 1]))
64
+ return 2 * (Y[i] / 2 + (Y[i + 1] / 2 - Y[i] / 2) * t);
65
+ return Y[i] + dy * t;
66
+ }
67
+ /**
68
+ * (y1 - y0) / h; where the difference of finite y overflows, 2 ((y1 / 2 - y0 / 2) / h), the same quotient rounded
69
+ * once (halving such large values is exact), so that a finite slope is not Infinity (#380)
70
+ */
71
+ function secant(y0, y1, h) {
72
+ const dy = y1 - y0;
73
+ if (!Number.isFinite(dy) && Number.isFinite(y0) && Number.isFinite(y1))
74
+ return 2 * ((y1 / 2 - y0 / 2) / h);
75
+ return dy / h;
76
+ }
77
+ /**
78
+ * The product of finite numbers (nonzero ones in the denominator) times 2^s, each factor taken as m 2^f, so that
79
+ * nothing overflows or underflows before the result (rounded a few times, in the normal range). For terms whose plain
80
+ * product leaves the range.
81
+ */
82
+ function scaledProduct(num, den, s) {
83
+ let p = 1;
84
+ let e = s;
85
+ for (const v of num) {
86
+ if (v === 0)
87
+ return 0 * p;
88
+ const f = Math.floor(Math.log2(Math.abs(v)));
89
+ p *= ldexp(v, -f);
90
+ e += f;
91
+ }
92
+ for (const v of den) {
93
+ const f = Math.floor(Math.log2(Math.abs(v)));
94
+ p /= ldexp(v, -f);
95
+ e -= f;
96
+ }
97
+ return ldexpWide(p, e);
52
98
  }
53
99
  /** Step value (1 - f) y_i + f y_{i+1}; a term with weight 0 is dropped, so an infinite y there does not give NaN. */
54
100
  function stepAt(Y, i, f) {
55
101
  const term = (w, yv) => (w === 0 ? 0 : w * yv);
56
102
  return term(1 - f, Y[i]) + term(f, Y[i + 1]);
57
103
  }
104
+ /**
105
+ * The interpolation method of approx, as R's pmatch(method, c("linear", "constant")): the full name or a unique
106
+ * prefix; anything else is R's "invalid interpolation method" (it was taken as "constant", #221)
107
+ */
108
+ function approxMethod(m) {
109
+ if (m === undefined)
110
+ return "linear";
111
+ if (typeof m === "string" && m.length > 0) {
112
+ const hit = ["linear", "constant"].filter((v) => v.startsWith(m));
113
+ if (hit.length === 1)
114
+ return hit[0];
115
+ }
116
+ throw new RangeError("invalid interpolation method");
117
+ }
118
+ /**
119
+ * The extrapolation rules [left, right] of approx: 1 or 2, given once or as a pair. Any other value (R takes every
120
+ * value other than 1 as rule 2, #221), NaN or more than two values (R's errors) is an error
121
+ */
122
+ function approxRule(rule) {
123
+ const r = typeof rule === "number" ? [rule] : Array.isArray(rule) ? rule : [];
124
+ const ok = (v) => v === 1 || v === 2;
125
+ if (r.length < 1 || r.length > 2 || !r.every(ok))
126
+ throw new RangeError("'rule' must be 1 or 2, or a pair of them");
127
+ return [r[0], r[r.length - 1]];
128
+ }
58
129
  /**
59
130
  * Linear or constant interpolation. Equivalent to R's `approx()`.
60
131
  *
@@ -66,7 +137,10 @@ function stepAt(Y, i, f) {
66
137
  * @category Numerical methods
67
138
  */
68
139
  export function approx(x, y, options = {}) {
69
- const { method = "linear", n = 50, f = 0, rule = 1, ties = "mean" } = options;
140
+ checkOptions(options, APPROX_KEYS, "approx"); // generated: option-keys.mjs
141
+ const { n = 50, f = 0, rule = 1, ties = "mean" } = options;
142
+ const method = approxMethod(options.method);
143
+ const [ruleLeft, ruleRight] = approxRule(rule);
70
144
  const pts = regularize(x, y, ties);
71
145
  const nx = pts.x.length;
72
146
  if (nx <= 1 && method === "linear")
@@ -76,14 +150,16 @@ export function approx(x, y, options = {}) {
76
150
  // As in R, f is checked only for the constant method
77
151
  if (method === "constant" && !(f >= 0 && f <= 1))
78
152
  throw new RangeError("approx(): invalid f value");
79
- const [ruleLeft, ruleRight] = typeof rule === "number" ? [rule, rule] : rule;
80
153
  const yleft = options.yleft ?? (ruleLeft === 1 ? NaN : pts.y[0]);
81
154
  const yright = options.yright ?? (ruleRight === 1 ? NaN : pts.y[nx - 1]);
82
155
  let xout;
83
156
  if (options.xout !== undefined)
84
157
  xout = Array.from(options.xout);
85
158
  else {
86
- if (n <= 0)
159
+ // (NaN and Infinity were an empty result and a JavaScript array error; issue #98)
160
+ if (!Number.isFinite(n) && !Number.isNaN(n))
161
+ throw new RangeError("'length.out' must be a finite number");
162
+ if (!(n > 0))
87
163
  throw new RangeError("'approx' requires n >= 1");
88
164
  xout = seqLength(pts.x[0], pts.x[nx - 1], n);
89
165
  }
@@ -120,7 +196,7 @@ function fmmCoef(x, y) {
120
196
  if (n < 2)
121
197
  return { b, c, d };
122
198
  if (n < 3) {
123
- b[0] = (y[1] - y[0]) / (x[1] - x[0]);
199
+ b[0] = secant(y[0], y[1], x[1] - x[0]);
124
200
  b[1] = b[0];
125
201
  return { b, c, d };
126
202
  }
@@ -273,7 +349,9 @@ function hymanCoef(x, y) {
273
349
  const sm = slope[i === 0 ? 0 : i - 1];
274
350
  const sp = slope[i === n - 1 ? n - 2 : i];
275
351
  const t = Math.min(Math.abs(sm), Math.abs(sp));
276
- const nonneg = sm * sp > 0 ? sp > 0 : b[i] >= 0;
352
+ // the signs compared, not the product sm sp > 0 (the same where it is finite and nonzero): the product of two
353
+ // small secants underflowed to 0 and the fmm slope chose the sign, negative for increasing data (issue #398)
354
+ const nonneg = (sm > 0 && sp > 0) || (sm < 0 && sp < 0) ? sp > 0 : b[i] >= 0;
277
355
  b[i] = nonneg ? Math.min(Math.max(0, b[i]), 3 * t) : Math.max(Math.min(0, b[i]), -3 * t);
278
356
  }
279
357
  for (let i = 0; i < n - 1; i++) {
@@ -287,6 +365,18 @@ function hymanCoef(x, y) {
287
365
  d[n - 1] = d[n - 2];
288
366
  return { b, c, d };
289
367
  }
368
+ /**
369
+ * The exponent k by which the sorted knots are divided when their range overflows (all finite, x_max - x_min
370
+ * infinite), else 0. The spline is then built in x / 2^k, where the spacings are finite, and evaluated at u / 2^k; a
371
+ * derivative of order d is brought back by 2^(-d k) (both exact for normal numbers). R gives 0, NaN or wrong values
372
+ * there (issue #125; spline, review 50).
373
+ */
374
+ function knotScale(x) {
375
+ const n = x.length;
376
+ if (n < 2 || !x.every(Number.isFinite) || Number.isFinite(x[n - 1] - x[0]))
377
+ return 0;
378
+ return Math.floor(Math.log2(maxOf(x.map(Math.abs))));
379
+ }
290
380
  /** Regularized data and coefficients of a b/c/d spline. */
291
381
  function cubicSpline(x, y, method, ties) {
292
382
  const pts = regularize(x, y, ties);
@@ -379,8 +469,13 @@ function evalCubic(sp, xq, deriv0) {
379
469
  * @category Numerical methods
380
470
  */
381
471
  export function spline(x, y, options = {}) {
472
+ checkOptions(options, SPLINE_KEYS, "spline"); // generated: option-keys.mjs
382
473
  const { method = "fmm", ties = "mean" } = options;
383
- const sp = cubicSpline(x, y, method, ties);
474
+ let sp = cubicSpline(x, y, method, ties);
475
+ // knots whose range overflows (x from -1e308 to 1e308; R gives NaN): the spline in x / 2^k, evaluated at xout / 2^k
476
+ const k = knotScale(sp.x);
477
+ if (k !== 0)
478
+ sp = cubicSpline(Array.from(x, (v) => ldexp(v, -k)), y, method, ties);
384
479
  let xout;
385
480
  if (options.xout !== undefined)
386
481
  xout = Array.from(options.xout);
@@ -388,37 +483,60 @@ export function spline(x, y, options = {}) {
388
483
  // n, xmin and xmax refer to the regularized data
389
484
  const nk = sp.x.length;
390
485
  const n = options.n ?? 3 * nk;
391
- if (n <= 0)
486
+ // (NaN and Infinity were an empty result and a JavaScript array error, as in approx; issue #98)
487
+ if (!Number.isFinite(n))
488
+ throw new RangeError("'length.out' must be a finite number");
489
+ if (!(n > 0))
392
490
  throw new RangeError("'spline' requires n >= 1");
393
- xout = seqLength(options.xmin ?? sp.x[0], options.xmax ?? sp.x[nk - 1], n);
491
+ xout = seqLength(options.xmin ?? ldexp(sp.x[0], k), options.xmax ?? ldexp(sp.x[nk - 1], k), n);
394
492
  }
395
- return { x: xout, y: evalCubic(sp, xout, 0) };
493
+ return { x: xout, y: evalCubic(sp, k === 0 ? xout : xout.map((v) => ldexp(v, -k)), 0) };
396
494
  }
397
495
  /**
398
496
  * The cubic spline through the points, as a function of `x` and the order of derivative (0 to 3; a fraction is
399
497
  * truncated, as R does). Equivalent to R's `splinefun()`. Except that the third derivative of `"monoH.FC"` is the
400
- * exact one (see {@link splinefunH}).
498
+ * exact one (see {@link splinefunH}). The order of derivative is the second argument of the function or its option
499
+ * `deriv` ({@link SplineFunction}).
401
500
  *
402
501
  * @example
403
502
  * ```ts
404
503
  * const s = splinefun([1, 2, 3, 4], [1, 4, 9, 16]);
405
- * s([2.5]); // [6.25]
406
- * s([2.5], 1); // [5]
504
+ * s([2.5]); // [6.25]
505
+ * s([2.5], 1); // [5]
506
+ * s([2.5], { deriv: 1 }); // [5]
407
507
  * ```
408
508
  *
409
509
  * @category Numerical methods
410
510
  */
411
511
  export function splinefun(x, y, options = {}) {
512
+ checkOptions(options, SPLINEFUN_KEYS, "splinefun"); // generated: option-keys.mjs
513
+ const f = splinefunOrder(x, y, options);
514
+ return (xq, ...args) => f(xq, optionalArgs(["deriv"], args, "the function from splinefun").deriv ?? 0);
515
+ }
516
+ /** splinefun as a function of x and the order of derivative */
517
+ function splinefunOrder(x, y, options) {
412
518
  const { method = "fmm", ties = "mean" } = options;
519
+ // knots whose range overflows: built in x / 2^k (see knotScale), as spline
413
520
  if (method === "monoH.FC") {
414
- const pts = regularize(x, y, ties);
521
+ let pts = regularize(x, y, ties);
415
522
  if (pts.x.length === 0)
416
523
  throw new RangeError("zero non-NA points");
524
+ const k = knotScale(pts.x);
525
+ if (k !== 0)
526
+ pts = regularize(Array.from(x, (v) => ldexp(v, -k)), y, ties);
527
+ // the slopes in units of 1 / 2^k
417
528
  const m = fritschCarlsonSlopes(pts.x, pts.y);
418
- return (xq, deriv = 0) => evalHermite(pts.x, pts.y, m, xq, deriv);
529
+ return (xq, deriv) => evalHermite(pts.x, pts.y, m, k, k, xq, deriv);
419
530
  }
420
- const sp = cubicSpline(x, y, method, ties);
421
- return (xq, deriv = 0) => evalCubic(sp, xq, deriv);
531
+ let sp = cubicSpline(x, y, method, ties);
532
+ const k = knotScale(sp.x);
533
+ if (k === 0)
534
+ return (xq, deriv) => evalCubic(sp, xq, deriv);
535
+ sp = cubicSpline(Array.from(x, (v) => ldexp(v, -k)), y, method, ties);
536
+ return (xq, deriv) => {
537
+ const d = checkDeriv(deriv);
538
+ return evalCubic(sp, Array.from(xq, (v) => ldexp(v, -k)), d).map((v) => ldexp(v, -d * k));
539
+ };
422
540
  }
423
541
  /**
424
542
  * Fritsch and Carlson's (1980) slopes: averages of the neighbouring secants, then, interval by interval from the left,
@@ -429,7 +547,7 @@ function fritschCarlsonSlopes(x, y) {
429
547
  if (n < 2)
430
548
  throw new RangeError("length(m) must be at least two");
431
549
  const S = Array.from({ length: n - 1 }, (_, k) => (y[k + 1] - y[k]) / (x[k + 1] - x[k]));
432
- const m = Array.from({ length: n }, (_, k) => (k === 0 ? S[0] : k === n - 1 ? S[n - 2] : (S[k - 1] + S[k]) / 2));
550
+ const m = Array.from({ length: n }, (_, k) => (k === 0 ? S[0] : k === n - 1 ? S[n - 2] : midpoint(S[k - 1], S[k])));
433
551
  for (let k = 0; k < n - 1; k++) {
434
552
  const Sk = S[k];
435
553
  if (Sk === 0) {
@@ -441,6 +559,25 @@ function fritschCarlsonSlopes(x, y) {
441
559
  const beta = m[k + 1] / Sk;
442
560
  const a = 2 * alpha + beta - 3;
443
561
  const b = alpha + 2 * beta - 3;
562
+ const inRange = Number.isFinite(alpha * (a + b)) && Number.isFinite(a * a) && Number.isFinite(alpha * alpha + beta * beta);
563
+ if (!inRange && Number.isFinite(m[k]) && Number.isFinite(m[k + 1]) && Number.isFinite(Sk)) {
564
+ // only where the ratios or their products overflow (secants 1e-200 and 1e200: beta = Inf, the test Inf < Inf
565
+ // false, and the spline overshot to -6.25e198; issue #397): alpha and beta divided by 2^g, the power of 2 of
566
+ // the larger. The test is homogeneous of degree 2 in (alpha, beta, 3) and the slopes of degree 0
567
+ const ex = (v) => (v === 0 ? -Infinity : Math.floor(Math.log2(Math.abs(v))));
568
+ const g = Math.max(ex(m[k]), ex(m[k + 1])) - ex(Sk);
569
+ const as = scaledProduct([m[k]], [Sk], -g);
570
+ const bs = scaledProduct([m[k + 1]], [Sk], -g);
571
+ const three = ldexpWide(3, -g);
572
+ const a2 = 2 * as + bs - three;
573
+ const b2 = as + 2 * bs - three;
574
+ if (a2 > 0 && b2 > 0 && as * (a2 + b2) < a2 * a2) {
575
+ const tau = (3 * Sk) / Math.sqrt(as * as + bs * bs);
576
+ m[k] = tau * as;
577
+ m[k + 1] = tau * bs;
578
+ }
579
+ continue;
580
+ }
444
581
  if (a > 0 && b > 0 && alpha * (a + b) < a * a) {
445
582
  const tau = (3 * Sk) / Math.sqrt(alpha * alpha + beta * beta);
446
583
  m[k] = tau * alpha;
@@ -449,13 +586,19 @@ function fritschCarlsonSlopes(x, y) {
449
586
  }
450
587
  return m;
451
588
  }
452
- /** Evaluates the cubic Hermite spline (or a derivative) with values y and slopes m at x; linear outside the data. */
453
- function evalHermite(x, y, m, xq, deriv0) {
589
+ /**
590
+ * Evaluates the cubic Hermite spline (or a derivative) with values y and slopes at x; linear outside the data. The
591
+ * knots x are those divided by 2^k and the slopes are m 2^-e (k = e = 0 in the ordinary range, where this is the plain
592
+ * formula): splinefunH keeps the given slopes (e = 0), monoH.FC its slopes in the divided coordinate (e = k), so that
593
+ * neither is rescaled where it could overflow or lose bits.
594
+ */
595
+ function evalHermite(x, y, m, k, e, xq, deriv0) {
454
596
  const deriv = checkDeriv(deriv0);
455
597
  const n = x.length;
456
- return Array.from(xq, (u) => {
457
- if (Number.isNaN(u))
598
+ return Array.from(xq, (u0) => {
599
+ if (Number.isNaN(u0))
458
600
  return NaN;
601
+ const u = k === 0 ? u0 : ldexp(u0, -k);
459
602
  // i = number of knots <= u
460
603
  let lo = 0;
461
604
  let hi = n;
@@ -468,8 +611,8 @@ function evalHermite(x, y, m, xq, deriv0) {
468
611
  }
469
612
  const i = lo;
470
613
  if (i === 0 || i === n) {
471
- const k = i === 0 ? 0 : n - 1;
472
- return deriv === 0 ? y[k] + m[k] * (u - x[k]) : deriv === 1 ? m[k] : 0;
614
+ const j = i === 0 ? 0 : n - 1;
615
+ return deriv === 0 ? y[j] + ldexp(m[j] * (u - x[j]), k - e) : deriv === 1 ? ldexp(m[j], -e) : 0;
473
616
  }
474
617
  const x0 = x[i - 1];
475
618
  const h = x[i] - x0;
@@ -479,15 +622,48 @@ function evalHermite(x, y, m, xq, deriv0) {
479
622
  const y1 = y[i];
480
623
  const m0 = m[i - 1];
481
624
  const m1 = m[i];
482
- const delta = (y1 - y0) / h;
625
+ // the secant in the units of the slopes
626
+ const delta = ldexp(secant(y0, y1, h), e - k);
483
627
  switch (deriv) {
484
628
  case 0: {
629
+ // h m_i in the original units
485
630
  const h01 = t * t * (3 - 2 * t);
486
- return y0 * (1 - h01) + h * m0 * (t * t1 * t1) + y1 * h01 + h * m1 * (t * t * t1);
631
+ // a term whose h m overflows before the small basis factor (h = 1e200, m = 1e200 at t = 1e-100 gave
632
+ // Inf - Inf for 1e300; issue #400): the product of the three factors with their exponents apart
633
+ const term = (mi, b) => {
634
+ const v = ldexp(h * mi, k - e) * b;
635
+ return Number.isFinite(v) || !Number.isFinite(mi) || !Number.isFinite(b) ? v : scaledProduct([h, mi, b], [], k - e);
636
+ };
637
+ return y0 * (1 - h01) + term(m0, t * t1 * t1) + y1 * h01 + term(m1, t * t * t1);
638
+ }
639
+ case 1: {
640
+ if (Number.isFinite(delta) || !Number.isFinite(y0) || !Number.isFinite(y1)) {
641
+ return ldexp(delta * (-6 * t * t1) + m0 * (t1 * (3 * t - 1)) + m1 * (t * (3 * t - 2)), -e);
642
+ }
643
+ // the secant overflows before the small basis factor (y1 - y0 = 1e200 over h = 1e-200 at t = 1e-100 gave
644
+ // Inf for 6e300; issue #401): (y1 - y0) times the factor over h with the exponents apart, in the original units
645
+ const dy = y1 - y0;
646
+ const d = Number.isFinite(dy) ? scaledProduct([dy, -6 * t * t1], [h], -k) : scaledProduct([y1 / 2 - y0 / 2, -6 * t * t1], [h], 1 - k);
647
+ return d + ldexp(m0 * (t1 * (3 * t - 1)) + m1 * (t * (3 * t - 2)), -e);
648
+ }
649
+ case 2: {
650
+ if (Number.isFinite(delta) || !Number.isFinite(y0) || !Number.isFinite(y1)) {
651
+ return ldexp((delta * (6 - 12 * t) + m0 * (6 * t - 4) + m1 * (6 * t - 2)) / h, -e - k);
652
+ }
653
+ // the secant overflows before the small basis factor (y1 - y0 = 1e200 over h = 1e-200 at t = 1/2 gave
654
+ // Inf * 0 = NaN for 0, R too; issue #466): as the first derivative (#401), (y1 - y0) times the factor over h^2
655
+ const dy = y1 - y0;
656
+ const d = Number.isFinite(dy) ? scaledProduct([dy, 6 - 12 * t], [h, h], -2 * k) : scaledProduct([y1 / 2 - y0 / 2, 6 - 12 * t], [h, h], 1 - 2 * k);
657
+ return d + ldexp((m0 * (6 * t - 4) + m1 * (6 * t - 2)) / h, -e - k);
658
+ }
659
+ default: {
660
+ const num = -12 * delta + 6 * m0 + 6 * m1;
661
+ const hh = h * h;
662
+ // h^2 outside the normal range (h = 1e200: num / Inf was 0 for 1.2e-199; issue #399): divided by h twice
663
+ if (!(hh >= 2 ** -1022 && hh < Infinity))
664
+ return ldexp(num / h / h, -e - 2 * k);
665
+ return ldexp(num / hh, -e - 2 * k);
487
666
  }
488
- case 1: return delta * (-6 * t * t1) + m0 * (t1 * (3 * t - 1)) + m1 * (t * (3 * t - 2));
489
- case 2: return (delta * (6 - 12 * t) + m0 * (6 * t - 4) + m1 * (6 * t - 2)) / h;
490
- default: return (-12 * delta + 6 * m0 + 6 * m1) / (h * h);
491
667
  }
492
668
  });
493
669
  }
@@ -495,11 +671,13 @@ function evalHermite(x, y, m, xq, deriv0) {
495
671
  * The cubic Hermite spline with values `y` and slopes `m` at the points `x`, as a function of `x` and the order of
496
672
  * derivative (0 to 3; a fraction is truncated, as R does); linear outside the data. Equivalent to R's `splinefunH()`.
497
673
  * Except for the third derivative: on [x_i, x_{i+1}] it is the exact (6 m_i + 6 m_{i+1} - 12 delta) / h^2, with
498
- * h = x_{i+1} - x_i and delta = (y_{i+1} - y_i) / h, where R divides by h only once (the two agree when h = 1).
674
+ * h = x_{i+1} - x_i and delta = (y_{i+1} - y_i) / h, where R divides by h only once (the two agree when h = 1). The
675
+ * order of derivative is the second argument of the function or its option `deriv` ({@link SplineFunction}).
499
676
  *
500
677
  * @example
501
678
  * ```ts
502
- * splinefunH([0, 2], [0, 0], [1, 1])([1], 3); // [3] (R: 6)
679
+ * splinefunH([0, 2], [0, 0], [1, 1])([1], 3); // [3] (R: 6)
680
+ * splinefunH([0, 2], [0, 0], [1, 1])([1], { deriv: 3 }); // [3]
503
681
  * ```
504
682
  *
505
683
  * @category Numerical methods
@@ -515,7 +693,10 @@ export function splinefunH(x, y, m) {
515
693
  for (let i = 1; i < n; i++)
516
694
  if (!(X[i] - X[i - 1] > 0))
517
695
  throw new RangeError("'x' must be *strictly* increasing (non - NA)");
518
- return (xq, deriv = 0) => evalHermite(X, Y, M, xq, deriv);
696
+ // knots whose range overflows: x / 2^k (see knotScale), the slopes as given
697
+ const k = knotScale(X);
698
+ const Xs = k === 0 ? X : X.map((v) => ldexp(v, -k));
699
+ return (xq, ...args) => evalHermite(Xs, Y, M, k, 0, xq, optionalArgs(["deriv"], args, "the function from splinefunH").deriv ?? 0);
519
700
  }
520
701
  /**
521
702
  * Lagrange interpolation in barycentric form through the points (xi, yi). Equivalent to `pracma::barylag()` in R.
@@ -535,17 +716,83 @@ export function barylag(xi, yi, x) {
535
716
  if (Y.length !== n)
536
717
  throw new RangeError("'xi' and 'yi' must have the same length");
537
718
  const xs = Array.from(x);
538
- const lo = Math.min(...X);
539
- const hi = Math.max(...X);
719
+ const lo = minOf(X);
720
+ const hi = maxOf(X);
540
721
  if (xs.some((v) => v < lo || v > hi))
541
722
  throw new RangeError("Some interpolation points outside the nodes.");
542
- const w = X.map((a, j) => {
723
+ // finite nodes whose range overflows: the weights and differences in x / 2, where every difference is finite (the
724
+ // barycentric ratio does not change with the scale of x). barylag([-1e308, 1e308], [-1, 1], [0]) was NaN (issue #215)
725
+ const half = Number.isFinite(lo) && Number.isFinite(hi) && !Number.isFinite(hi - lo);
726
+ const Xc = half ? X.map((a) => a / 2) : X;
727
+ // The weights 1 / prod (x_j - x_k), each product kept as m 2^e (renormalised beyond 2^±500), then all of them by one
728
+ // common power of 2 (which leaves the interpolant unchanged): the products of nodes of 1e200 overflowed and every
729
+ // weight was 0, the result NaN (pracma's too; issue #14). Without renormalisation the weights are as before
730
+ const parts = Xc.map((a, j) => {
543
731
  let p = 1;
544
- for (let k = 0; k < n; k++)
545
- if (k !== j)
546
- p *= a - X[k];
547
- return 1 / p;
732
+ let e = 0;
733
+ for (let k = 0; k < n; k++) {
734
+ if (k === j)
735
+ continue;
736
+ const d = a - Xc[k];
737
+ const q = p * d;
738
+ if (p !== 0 && d !== 0 && Number.isFinite(d) && !(Math.abs(q) >= 2 ** -1022 && Math.abs(q) < Infinity)) {
739
+ // only where the product leaves the normal range (it underflowed to 0 before the check below: nodes 0,
740
+ // 2^-250, 2^-249, 2^-600 gave the weight 1/0 and NaN; issue #402): both factors as m 2^f, multiplied exactly
741
+ const fp = Math.floor(Math.log2(Math.abs(p)));
742
+ const fd = Math.floor(Math.log2(Math.abs(d)));
743
+ p = ldexp(p, -fp) * ldexp(d, -fd);
744
+ e += fp + fd;
745
+ continue;
746
+ }
747
+ p = q;
748
+ const m = Math.abs(p);
749
+ if (m > 2 ** 500 || (m < 2 ** -500 && m > 0)) {
750
+ const f = Math.floor(Math.log2(m));
751
+ p = ldexp(p, -f);
752
+ e += f;
753
+ }
754
+ }
755
+ return { p, e };
548
756
  });
757
+ const shift = parts.reduce((s, q) => Math.max(s, -q.e), -Infinity);
758
+ const w = parts.map((q) => ldexp(1 / q.p, -q.e - shift));
759
+ const finiteData = X.every(Number.isFinite) && Y.every(Number.isFinite);
760
+ // power of 2 of the largest |y_j|, so that the sum of the first form below does not overflow
761
+ const yTop = finiteData ? Y.reduce((s, y) => (y === 0 ? s : Math.max(s, Math.floor(Math.log2(Math.abs(y))))), -Infinity) : 0;
762
+ // The first barycentric form l(u) sum_j w_j y_j / (u - x_j), l(u) = prod_j (u - x_j), with every factor as m 2^f:
763
+ // l(u) as a mantissa and an exponent, the terms 1 / (p_j (u - x_j)) y_j over the powers of 2 of the largest term and
764
+ // of the largest |y_j|. undefined where a difference is 0 (u a node after halving)
765
+ const firstForm = (u) => {
766
+ if (yTop === -Infinity)
767
+ return 0;
768
+ let lm = 1;
769
+ let le = 0;
770
+ const terms = [];
771
+ for (let j = 0; j < n; j++) {
772
+ const d = u - Xc[j];
773
+ if (d === 0)
774
+ return undefined;
775
+ const f = Math.floor(Math.log2(Math.abs(d)));
776
+ const dm = ldexp(d, -f);
777
+ lm *= dm;
778
+ const g = Math.floor(Math.log2(Math.abs(lm)));
779
+ lm = ldexp(lm, -g);
780
+ le += f + g;
781
+ const r = 1 / parts[j].p / dm;
782
+ if (!Number.isFinite(r) || r === 0)
783
+ return undefined;
784
+ const fr = Math.floor(Math.log2(Math.abs(r)));
785
+ terms.push({ r: ldexp(r, -fr), x: fr - parts[j].e - f });
786
+ }
787
+ const top = terms.reduce((s, q) => Math.max(s, q.x), -Infinity);
788
+ let s = 0;
789
+ for (let j = 0; j < n; j++)
790
+ s += ldexp(terms[j].r, terms[j].x - top) * ldexp(Y[j], -yTop);
791
+ if (s === 0)
792
+ return 0;
793
+ const fs = Math.floor(Math.log2(Math.abs(s)));
794
+ return ldexpWide(lm * ldexp(s, -fs), le + top + yTop + fs);
795
+ };
549
796
  return xs.map((v) => {
550
797
  let num = 0;
551
798
  let den = 0;
@@ -553,13 +800,53 @@ export function barylag(xi, yi, x) {
553
800
  const at = X.lastIndexOf(v);
554
801
  if (at >= 0)
555
802
  return Y[at];
803
+ let sumAbs = 0;
804
+ let sumAbsNum = 0;
556
805
  for (let j = 0; j < n; j++) {
557
- const diff = v - X[j];
806
+ const diff = (half ? v / 2 : v) - Xc[j];
558
807
  const t = w[j] / diff;
559
808
  num += t * Y[j];
560
809
  den += t;
810
+ sumAbs += Math.abs(t);
811
+ sumAbsNum += Math.abs(t * Y[j]);
812
+ }
813
+ const r = num / den;
814
+ // The denominator lost to cancellation while the numerator did not: a rounded sum of the t_j is not below 2^-53
815
+ // of the largest |t_j| unless large terms cancelled exactly, leaving only terms below their rounding error. The
816
+ // nodes 0, 2^-250, 2^-249, 2^-600 at 2^-300 have t_0 = -2^300 and t_3 = 2^300 cancelling to den = 0, so y = x gave
817
+ // Infinity for 2^-300 (pracma NaN; issue #467). There the first form l(x) sum w_j y_j / (x - x_j) (no cancelling
818
+ // denominator). Data whose numerator cancels too (a constant) keep the second form, which reproduces them
819
+ if (finiteData &&
820
+ Number.isFinite(sumAbs) &&
821
+ sumAbs > 0 &&
822
+ Math.abs(den) < ldexp(sumAbs, -100) &&
823
+ Number.isFinite(sumAbsNum) &&
824
+ Math.abs(num) >= ldexp(sumAbsNum, -26)) {
825
+ const first = firstForm(half ? v / 2 : v);
826
+ if (first !== undefined)
827
+ return first;
561
828
  }
562
- return num / den;
829
+ if (Number.isFinite(r) || !finiteData)
830
+ return r;
831
+ // only where the plain quotient is not finite for finite data: w_j / (x - x_j) overflowed (the nodes 0, 2^-250,
832
+ // 2^-249, 2^-600 at 2^-1074 gave Inf / Inf; issue #402). The terms from the products m 2^e and the differences as
833
+ // m 2^f, divided by the power of 2 of the largest term (which leaves the quotient unchanged)
834
+ const terms = parts.map((q, j) => {
835
+ const diff = (half ? v / 2 : v) - Xc[j];
836
+ const f = Math.floor(Math.log2(Math.abs(diff)));
837
+ return { r: 1 / q.p / ldexp(diff, -f), x: -q.e - f };
838
+ });
839
+ if (!terms.every((q) => Number.isFinite(q.r) && Number.isFinite(q.x)))
840
+ return r;
841
+ const top = terms.reduce((s, q) => Math.max(s, q.x), -Infinity);
842
+ let num2 = 0;
843
+ let den2 = 0;
844
+ for (let j = 0; j < n; j++) {
845
+ const t = ldexp(terms[j].r, terms[j].x - top);
846
+ num2 += t * Y[j];
847
+ den2 += t;
848
+ }
849
+ return num2 / den2;
563
850
  });
564
851
  }
565
852
  /**
@@ -582,9 +869,40 @@ export function hermiteInterp(xi, yi, di, x) {
582
869
  const n = X.length;
583
870
  if (Y.length !== n || D.length !== n)
584
871
  throw new RangeError("'xi', 'yi' and 'di' must have the same length");
585
- const z = X.flatMap((v) => [v, v]);
872
+ // the divided differences of order j scale as 1 / x^j: for large nodes they underflow (hermiteInterp([-1e200, 1e200],
873
+ // [-1, 1], [0, 0], [0.5e200]) was -1 for 0.6875, issue #216 follow-up), for tiny ones they overflow, and where the
874
+ // range of finite nodes overflows the separations are infinite and the quotients 0 (hermiteInterp([-1e308, 1e308],
875
+ // [-1, 1], [0, 0], [0]) was -1, issue #216). Only then (a quotient of finite, nonzero numbers that is not finite or
876
+ // below the normal range, or a range that overflows), the polynomial in x / 2^k with 2^k near the largest node
877
+ // (derivatives times 2^k, exact), where the nodes are of order 1. Otherwise the same bits as the unscaled table.
878
+ let k0 = knotScale([...X].sort((a, b) => a - b));
879
+ let table = k0 === 0 ? hermiteTable(X, Y, D) : undefined;
880
+ if (table?.lost && [X, Y, D].every((v) => v.every(Number.isFinite))) {
881
+ const k = Math.floor(Math.log2(maxOf(X.map(Math.abs))));
882
+ if (k !== 0)
883
+ [k0, table] = [k, undefined];
884
+ }
885
+ if (table === undefined)
886
+ table = hermiteTable(X.map((v) => ldexp(v, -k0)), Y, D.map((v) => ldexp(v, k0)));
887
+ const { z, coef } = table;
586
888
  const m = 2 * n;
587
- // divided-difference table, column by column (in place)
889
+ return Array.from(x, (v) => {
890
+ let r = coef[m - 1];
891
+ const u = k0 === 0 ? v : ldexp(v, -k0);
892
+ for (let k = m - 2; k >= 0; k--)
893
+ r = r * (u - z[k]) + coef[k];
894
+ return r;
895
+ });
896
+ }
897
+ /**
898
+ * The divided-difference table of hermiteInterp on the doubled nodes; `lost` where a quotient of finite, nonzero
899
+ * numbers is not finite or falls below the normal range.
900
+ */
901
+ function hermiteTable(X, Y, D) {
902
+ const z = X.flatMap((v) => [v, v]);
903
+ const m = z.length;
904
+ let lost = false;
905
+ // divided-difference table, column by column
588
906
  const q = Y.flatMap((v) => [v, v]);
589
907
  const coef = [q[0]];
590
908
  let col = q.slice();
@@ -593,16 +911,18 @@ export function hermiteInterp(xi, yi, di, x) {
593
911
  for (let i = 0; i < m - k; i++) {
594
912
  if (k === 1 && z[i + 1] === z[i])
595
913
  next.push(D[i >> 1]);
596
- else
597
- next.push((col[i + 1] - col[i]) / (z[i + k] - z[i]));
914
+ else {
915
+ const num = col[i + 1] - col[i];
916
+ const den = z[i + k] - z[i];
917
+ const r = secant(col[i], col[i + 1], den);
918
+ const finite = Number.isFinite(col[i + 1]) && Number.isFinite(col[i]);
919
+ if (finite && num !== 0 && den !== 0 && !(Math.abs(r) >= 2 ** -1022 && Math.abs(r) < Infinity))
920
+ lost = true;
921
+ next.push(r);
922
+ }
598
923
  }
599
924
  coef.push(next[0]);
600
925
  col = next;
601
926
  }
602
- return Array.from(x, (v) => {
603
- let r = coef[m - 1];
604
- for (let k = m - 2; k >= 0; k--)
605
- r = r * (v - z[k]) + coef[k];
606
- return r;
607
- });
927
+ return { z, coef, lost };
608
928
  }