@numero-uno-jpn/rstats 0.15.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CHANGELOG.md +280 -0
  2. package/README.ja.md +40 -33
  3. package/README.md +36 -28
  4. package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
  5. package/dist/chunks/chunk-5UQCRBAG.js +2 -0
  6. package/dist/chunks/chunk-6CSTWA5E.js +2 -0
  7. package/dist/chunks/chunk-72Y3HZID.js +2 -0
  8. package/dist/chunks/chunk-BG2KLEHM.js +2 -0
  9. package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
  10. package/dist/chunks/chunk-FLJNSXSW.js +2 -0
  11. package/dist/chunks/chunk-GM53LWSR.js +2 -0
  12. package/dist/chunks/chunk-JBCA56ZS.js +3 -0
  13. package/dist/chunks/chunk-K3RJAD2T.js +2 -0
  14. package/dist/chunks/chunk-KAZRWIB5.js +2 -0
  15. package/dist/chunks/chunk-KBVVIMXX.js +3 -0
  16. package/dist/chunks/chunk-N3SIFCZX.js +2 -0
  17. package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
  18. package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
  19. package/dist/chunks/chunk-SYWOBOTR.js +2 -0
  20. package/dist/chunks/chunk-URIO5LY5.js +2 -0
  21. package/dist/chunks/chunk-VTUGG2SV.js +2 -0
  22. package/dist/chunks/chunk-W26LRYOJ.js +2 -0
  23. package/dist/chunks/chunk-XHETEYVC.js +2 -0
  24. package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
  25. package/dist/chunks/chunk-ZGABZMWX.js +2 -0
  26. package/dist/data/grouping.js +20 -5
  27. package/dist/descriptive/basic.js +90 -8
  28. package/dist/descriptive/cov.js +12 -4
  29. package/dist/descriptive/dataFrames.d.ts +4 -2
  30. package/dist/descriptive/dataFrames.js +56 -18
  31. package/dist/descriptive/factanal.js +16 -7
  32. package/dist/descriptive/hist.d.ts +8 -5
  33. package/dist/descriptive/hist.js +71 -31
  34. package/dist/descriptive/missing.js +3 -1
  35. package/dist/descriptive/moments.js +72 -19
  36. package/dist/descriptive/omega.d.ts +1 -1
  37. package/dist/descriptive/omega.js +68 -9
  38. package/dist/descriptive/pivot.d.ts +21 -9
  39. package/dist/descriptive/pivot.js +161 -35
  40. package/dist/descriptive/quantile.js +2 -1
  41. package/dist/descriptive/rank.js +4 -1
  42. package/dist/descriptive/table.d.ts +3 -2
  43. package/dist/descriptive/table.js +24 -9
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +19 -2
  46. package/dist/distributions/beta.js +35 -5
  47. package/dist/distributions/binomial.js +37 -14
  48. package/dist/distributions/bvnorm.js +11 -2
  49. package/dist/distributions/cauchy.js +87 -8
  50. package/dist/distributions/chisq.js +7 -3
  51. package/dist/distributions/exponential.js +11 -1
  52. package/dist/distributions/f.js +73 -22
  53. package/dist/distributions/gamma.js +61 -6
  54. package/dist/distributions/geometric.js +53 -14
  55. package/dist/distributions/hypergeometric.d.ts +5 -1
  56. package/dist/distributions/hypergeometric.js +93 -6
  57. package/dist/distributions/invgamma.js +6 -1
  58. package/dist/distributions/kumaraswamy.js +22 -4
  59. package/dist/distributions/laplace.js +31 -7
  60. package/dist/distributions/logistic.js +11 -2
  61. package/dist/distributions/lognormal.js +20 -3
  62. package/dist/distributions/multinomial.js +54 -11
  63. package/dist/distributions/nbeta.js +128 -35
  64. package/dist/distributions/nchisq.js +85 -14
  65. package/dist/distributions/negbinomial.js +100 -18
  66. package/dist/distributions/normal.js +35 -5
  67. package/dist/distributions/nt.d.ts +28 -3
  68. package/dist/distributions/nt.js +536 -35
  69. package/dist/distributions/pareto.js +9 -1
  70. package/dist/distributions/poisson.js +28 -3
  71. package/dist/distributions/signrank.js +7 -4
  72. package/dist/distributions/summary.js +450 -60
  73. package/dist/distributions/t.js +55 -3
  74. package/dist/distributions/triangular.js +45 -13
  75. package/dist/distributions/tukey.js +21 -2
  76. package/dist/distributions/uniform.js +2 -0
  77. package/dist/distributions/weibull.js +33 -3
  78. package/dist/distributions/wilcox.d.ts +9 -3
  79. package/dist/distributions/wilcox.js +155 -26
  80. package/dist/distributions.js +2 -2
  81. package/dist/htest/agreement.d.ts +3 -2
  82. package/dist/htest/agreement.js +76 -14
  83. package/dist/htest/ansariTest.d.ts +6 -1
  84. package/dist/htest/ansariTest.js +75 -8
  85. package/dist/htest/aov.d.ts +1 -1
  86. package/dist/htest/aov.js +48 -34
  87. package/dist/htest/binomTest.d.ts +5 -0
  88. package/dist/htest/binomTest.js +41 -17
  89. package/dist/htest/brunnerMunzelTest.d.ts +4 -3
  90. package/dist/htest/brunnerMunzelTest.js +7 -5
  91. package/dist/htest/chisqTest.d.ts +2 -1
  92. package/dist/htest/chisqTest.js +130 -43
  93. package/dist/htest/cor.d.ts +2 -1
  94. package/dist/htest/cor.js +17 -19
  95. package/dist/htest/core/ansari.d.ts +9 -0
  96. package/dist/htest/core/ansari.js +21 -1
  97. package/dist/htest/core/kolmogorov.d.ts +25 -0
  98. package/dist/htest/core/kolmogorov.js +123 -0
  99. package/dist/htest/core/mantelhaen.js +6 -4
  100. package/dist/htest/core/shapiro.d.ts +1 -1
  101. package/dist/htest/core/shapiro.js +5 -1
  102. package/dist/htest/dunnett.js +14 -5
  103. package/dist/htest/effectSize.d.ts +2 -0
  104. package/dist/htest/effectSize.js +91 -29
  105. package/dist/htest/fisherTest.d.ts +2 -2
  106. package/dist/htest/fisherTest.js +36 -18
  107. package/dist/htest/groups.d.ts +7 -0
  108. package/dist/htest/groups.js +21 -4
  109. package/dist/htest/ksTest.d.ts +3 -1
  110. package/dist/htest/ksTest.js +23 -2
  111. package/dist/htest/leveneTest.js +19 -3
  112. package/dist/htest/mantelhaenTest.js +125 -25
  113. package/dist/htest/mcnemarTest.js +32 -11
  114. package/dist/htest/multipleComparisons.d.ts +8 -1
  115. package/dist/htest/multipleComparisons.js +44 -21
  116. package/dist/htest/normalityTests.js +44 -10
  117. package/dist/htest/onewayTest.js +96 -5
  118. package/dist/htest/pAdjust.d.ts +3 -2
  119. package/dist/htest/pAdjust.js +38 -6
  120. package/dist/htest/pairwise.d.ts +1 -1
  121. package/dist/htest/pairwise.js +17 -15
  122. package/dist/htest/poissonTest.d.ts +1 -1
  123. package/dist/htest/poissonTest.js +111 -59
  124. package/dist/htest/polycor.js +27 -7
  125. package/dist/htest/power.d.ts +11 -1
  126. package/dist/htest/power.js +112 -8
  127. package/dist/htest/propTest.js +21 -4
  128. package/dist/htest/pwr.js +121 -24
  129. package/dist/htest/rankTests.js +29 -5
  130. package/dist/htest/tTest.js +44 -21
  131. package/dist/htest/trendTests.d.ts +7 -3
  132. package/dist/htest/trendTests.js +114 -20
  133. package/dist/htest/types.d.ts +5 -0
  134. package/dist/htest/types.js +7 -0
  135. package/dist/htest/varTest.js +45 -14
  136. package/dist/htest/wilcoxTest.js +114 -21
  137. package/dist/integrate/quadpack.js +27 -5
  138. package/dist/internal/covmat.d.ts +5 -0
  139. package/dist/internal/covmat.js +20 -0
  140. package/dist/internal/ddexp.d.ts +23 -1
  141. package/dist/internal/ddexp.js +86 -6
  142. package/dist/internal/discrete.d.ts +14 -0
  143. package/dist/internal/discrete.js +78 -5
  144. package/dist/internal/extremes.d.ts +9 -0
  145. package/dist/internal/extremes.js +24 -0
  146. package/dist/internal/fround.js +13 -4
  147. package/dist/internal/integer.d.ts +9 -0
  148. package/dist/internal/integer.js +12 -0
  149. package/dist/internal/invert.d.ts +5 -0
  150. package/dist/internal/invert.js +25 -7
  151. package/dist/internal/noncentral.d.ts +7 -0
  152. package/dist/internal/noncentral.js +9 -0
  153. package/dist/internal/poissonMixture.js +29 -6
  154. package/dist/internal/scaledInverse.d.ts +10 -0
  155. package/dist/internal/scaledInverse.js +22 -0
  156. package/dist/internal/seq.js +15 -2
  157. package/dist/internal/summary.d.ts +90 -0
  158. package/dist/internal/summary.js +458 -39
  159. package/dist/internal/uniroot.d.ts +7 -0
  160. package/dist/internal/uniroot.js +28 -3
  161. package/dist/linalg/basic.d.ts +3 -1
  162. package/dist/linalg/basic.js +51 -7
  163. package/dist/linalg/chol.js +4 -1
  164. package/dist/linalg/dot.d.ts +29 -0
  165. package/dist/linalg/dot.js +132 -0
  166. package/dist/linalg/eigen.d.ts +6 -1
  167. package/dist/linalg/eigen.js +71 -14
  168. package/dist/linalg/expm.d.ts +3 -2
  169. package/dist/linalg/expm.js +109 -15
  170. package/dist/linalg/kappa.js +58 -10
  171. package/dist/linalg/lu.d.ts +2 -1
  172. package/dist/linalg/lu.js +35 -5
  173. package/dist/linalg/matrix.d.ts +14 -0
  174. package/dist/linalg/matrix.js +24 -0
  175. package/dist/linalg/ops.js +60 -13
  176. package/dist/linalg/qr.d.ts +2 -1
  177. package/dist/linalg/qr.js +91 -23
  178. package/dist/linalg/schur.js +11 -3
  179. package/dist/linalg/solve.d.ts +6 -1
  180. package/dist/linalg/solve.js +147 -26
  181. package/dist/linalg/svd.d.ts +9 -2
  182. package/dist/linalg/svd.js +29 -11
  183. package/dist/linalg.js +2 -2
  184. package/dist/mixed.js +4 -4
  185. package/dist/models/anovaSequential.d.ts +16 -1
  186. package/dist/models/anovaSequential.js +124 -25
  187. package/dist/models/aovEz.js +140 -30
  188. package/dist/models/aovStrata.js +55 -22
  189. package/dist/models/carAnova.d.ts +1 -1
  190. package/dist/models/carAnova.js +83 -32
  191. package/dist/models/coxph.js +148 -66
  192. package/dist/models/estimable.d.ts +15 -0
  193. package/dist/models/estimable.js +68 -0
  194. package/dist/models/formula.d.ts +1 -1
  195. package/dist/models/formula.js +26 -8
  196. package/dist/models/glm.d.ts +35 -5
  197. package/dist/models/glm.js +398 -55
  198. package/dist/models/glmAnova.js +84 -13
  199. package/dist/models/glmConfint.d.ts +1 -1
  200. package/dist/models/glmConfint.js +115 -27
  201. package/dist/models/glmFamily.d.ts +10 -0
  202. package/dist/models/glmFamily.js +244 -40
  203. package/dist/models/lm.d.ts +12 -1
  204. package/dist/models/lm.js +235 -36
  205. package/dist/models/lmer.d.ts +20 -1
  206. package/dist/models/lmer.js +109 -27
  207. package/dist/models/lmerAnova.js +37 -4
  208. package/dist/models/lmerHypotheses.d.ts +6 -2
  209. package/dist/models/lmerHypotheses.js +14 -2
  210. package/dist/models/lmerTest.d.ts +9 -2
  211. package/dist/models/lmerTest.js +64 -19
  212. package/dist/models/mauchly.d.ts +4 -1
  213. package/dist/models/mauchly.js +34 -13
  214. package/dist/models/mixedStructure.js +6 -0
  215. package/dist/models/modelFrame.js +8 -2
  216. package/dist/models/modelMatrix.d.ts +3 -1
  217. package/dist/models/modelMatrix.js +40 -15
  218. package/dist/models/scaledTables.d.ts +8 -0
  219. package/dist/models/scaledTables.js +6 -0
  220. package/dist/models/survival.d.ts +6 -1
  221. package/dist/models/survival.js +67 -27
  222. package/dist/models/tiedTimes.d.ts +2 -0
  223. package/dist/models/tiedTimes.js +34 -0
  224. package/dist/numerics/deriv.d.ts +1 -1
  225. package/dist/numerics/deriv.js +64 -8
  226. package/dist/numerics/integrate.d.ts +9 -1
  227. package/dist/numerics/integrate.js +103 -16
  228. package/dist/numerics/interp.d.ts +8 -2
  229. package/dist/numerics/interp.js +352 -50
  230. package/dist/numerics/ode.js +55 -1
  231. package/dist/numerics.js +2 -2
  232. package/dist/optim/localmin.js +4 -0
  233. package/dist/optim/optim.d.ts +3 -1
  234. package/dist/optim/optim.js +80 -8
  235. package/dist/random/beta.js +53 -4
  236. package/dist/random/binomial.d.ts +14 -3
  237. package/dist/random/binomial.js +59 -24
  238. package/dist/random/continuous.js +33 -5
  239. package/dist/random/extra.js +42 -9
  240. package/dist/random/gamma.d.ts +4 -1
  241. package/dist/random/gamma.js +36 -8
  242. package/dist/random/hyper.js +9 -6
  243. package/dist/random/mt.js +17 -2
  244. package/dist/random/poisson.js +26 -3
  245. package/dist/random/r2dtable.d.ts +8 -1
  246. package/dist/random/r2dtable.js +24 -3
  247. package/dist/random/rank.d.ts +2 -0
  248. package/dist/random/rank.js +44 -4
  249. package/dist/random/sample.d.ts +12 -2
  250. package/dist/random/sample.js +57 -20
  251. package/dist/random/streams.js +4 -2
  252. package/dist/rstats.js +14 -14
  253. package/dist/special/besselIK.d.ts +12 -0
  254. package/dist/special/besselIK.js +168 -23
  255. package/dist/special/besselJY.d.ts +11 -1
  256. package/dist/special/besselJY.js +127 -19
  257. package/dist/special/besselSeries.d.ts +27 -0
  258. package/dist/special/besselSeries.js +45 -2
  259. package/dist/special/beta.js +11 -1
  260. package/dist/special/choose.js +17 -8
  261. package/dist/special/dd.js +122 -18
  262. package/dist/special/extra.js +14 -2
  263. package/dist/special/gamma.js +15 -2
  264. package/dist/special/igam.js +33 -6
  265. package/dist/special/incbet.js +100 -10
  266. package/dist/special/incbetLargeA.js +7 -2
  267. package/dist/special/incbetPrefactor.d.ts +5 -0
  268. package/dist/special/incbetPrefactor.js +14 -3
  269. package/dist/special/incbetTemme.d.ts +7 -0
  270. package/dist/special/incbetTemme.js +45 -12
  271. package/dist/special/loader.d.ts +1 -1
  272. package/dist/special/loader.js +179 -33
  273. package/dist/special/log1pmx.js +4 -0
  274. package/dist/special.js +2 -2
  275. package/dist/tests.js +11 -11
  276. package/llms.txt +12 -6
  277. package/package.json +1 -1
  278. package/dist/chunks/chunk-2CUKVVRO.js +0 -2
  279. package/dist/chunks/chunk-3WQCKGKP.js +0 -2
  280. package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
  281. package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
  282. package/dist/chunks/chunk-D4F7GQAY.js +0 -2
  283. package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
  284. package/dist/chunks/chunk-HBMHR5SS.js +0 -2
  285. package/dist/chunks/chunk-IBPWRQIF.js +0 -2
  286. package/dist/chunks/chunk-JLAH3X77.js +0 -2
  287. package/dist/chunks/chunk-LG74QY5U.js +0 -2
  288. package/dist/chunks/chunk-PEYGUK32.js +0 -2
  289. package/dist/chunks/chunk-Q4PGYESP.js +0 -2
  290. package/dist/chunks/chunk-RCAL4VHM.js +0 -3
  291. package/dist/chunks/chunk-SREPSVTT.js +0 -2
  292. package/dist/chunks/chunk-UFT662QZ.js +0 -2
  293. package/dist/chunks/chunk-VWJ74UHC.js +0 -2
  294. package/dist/chunks/chunk-XNPU54NH.js +0 -2
  295. package/dist/chunks/chunk-XPLDEK6D.js +0 -2
  296. package/dist/chunks/chunk-YGT4P7EU.js +0 -2
  297. package/dist/chunks/chunk-YVREYVI2.js +0 -2
@@ -13,9 +13,10 @@
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
18
  import { findInterval } from "../descriptive/table.js";
19
+ import { maxOf, midpoint, minOf } from "../internal/extremes.js";
19
20
  /**
20
21
  * 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
22
  * one point whose y is `ties` of the run's y values (a single point keeps its y).
@@ -29,8 +30,8 @@ function regularize(x, y, ties = "mean") {
29
30
  idx.push(i);
30
31
  idx.sort((a, b) => x[a] - x[b]); // stable
31
32
  const merge = typeof ties === "function" ? ties
32
- : ties === "min" ? (v) => Math.min(...v)
33
- : ties === "max" ? (v) => Math.max(...v)
33
+ : ties === "min" ? (v) => minOf(v)
34
+ : ties === "max" ? (v) => maxOf(v)
34
35
  : mean;
35
36
  const xs = [];
36
37
  const ys = [];
@@ -47,14 +48,78 @@ function regularize(x, y, ties = "mean") {
47
48
  }
48
49
  /** 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
50
  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;
51
+ let t = (v - X[i]) / (X[i + 1] - X[i]);
52
+ // differences of finite values that overflow are taken in half coordinates (approx(c(-1e308, 1e308), c(0, 1),
53
+ // xout = 0) was 0, and approx(c(0, 1), c(-1e308, 1e308), xout = 0.5) Infinity; R too)
54
+ if (!Number.isFinite(X[i + 1] - X[i]) || !Number.isFinite(v - X[i]))
55
+ t = (v / 2 - X[i] / 2) / (X[i + 1] / 2 - X[i] / 2);
56
+ const dy = Y[i + 1] - Y[i];
57
+ if (!Number.isFinite(dy) && Number.isFinite(Y[i]) && Number.isFinite(Y[i + 1]))
58
+ return 2 * (Y[i] / 2 + (Y[i + 1] / 2 - Y[i] / 2) * t);
59
+ return Y[i] + dy * t;
60
+ }
61
+ /**
62
+ * (y1 - y0) / h; where the difference of finite y overflows, 2 ((y1 / 2 - y0 / 2) / h), the same quotient rounded
63
+ * once (halving such large values is exact), so that a finite slope is not Infinity (#380)
64
+ */
65
+ function secant(y0, y1, h) {
66
+ const dy = y1 - y0;
67
+ if (!Number.isFinite(dy) && Number.isFinite(y0) && Number.isFinite(y1))
68
+ return 2 * ((y1 / 2 - y0 / 2) / h);
69
+ return dy / h;
70
+ }
71
+ /**
72
+ * The product of finite numbers (nonzero ones in the denominator) times 2^s, each factor taken as m 2^f, so that
73
+ * nothing overflows or underflows before the result (rounded a few times, in the normal range). For terms whose plain
74
+ * product leaves the range.
75
+ */
76
+ function scaledProduct(num, den, s) {
77
+ let p = 1;
78
+ let e = s;
79
+ for (const v of num) {
80
+ if (v === 0)
81
+ return 0 * p;
82
+ const f = Math.floor(Math.log2(Math.abs(v)));
83
+ p *= ldexp(v, -f);
84
+ e += f;
85
+ }
86
+ for (const v of den) {
87
+ const f = Math.floor(Math.log2(Math.abs(v)));
88
+ p /= ldexp(v, -f);
89
+ e -= f;
90
+ }
91
+ return ldexpWide(p, e);
52
92
  }
53
93
  /** 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
94
  function stepAt(Y, i, f) {
55
95
  const term = (w, yv) => (w === 0 ? 0 : w * yv);
56
96
  return term(1 - f, Y[i]) + term(f, Y[i + 1]);
57
97
  }
98
+ /**
99
+ * The interpolation method of approx, as R's pmatch(method, c("linear", "constant")): the full name or a unique
100
+ * prefix; anything else is R's "invalid interpolation method" (it was taken as "constant", #221)
101
+ */
102
+ function approxMethod(m) {
103
+ if (m === undefined)
104
+ return "linear";
105
+ if (typeof m === "string" && m.length > 0) {
106
+ const hit = ["linear", "constant"].filter((v) => v.startsWith(m));
107
+ if (hit.length === 1)
108
+ return hit[0];
109
+ }
110
+ throw new RangeError("invalid interpolation method");
111
+ }
112
+ /**
113
+ * The extrapolation rules [left, right] of approx: 1 or 2, given once or as a pair. Any other value (R takes every
114
+ * value other than 1 as rule 2, #221), NaN or more than two values (R's errors) is an error
115
+ */
116
+ function approxRule(rule) {
117
+ const r = typeof rule === "number" ? [rule] : Array.isArray(rule) ? rule : [];
118
+ const ok = (v) => v === 1 || v === 2;
119
+ if (r.length < 1 || r.length > 2 || !r.every(ok))
120
+ throw new RangeError("'rule' must be 1 or 2, or a pair of them");
121
+ return [r[0], r[r.length - 1]];
122
+ }
58
123
  /**
59
124
  * Linear or constant interpolation. Equivalent to R's `approx()`.
60
125
  *
@@ -66,7 +131,9 @@ function stepAt(Y, i, f) {
66
131
  * @category Numerical methods
67
132
  */
68
133
  export function approx(x, y, options = {}) {
69
- const { method = "linear", n = 50, f = 0, rule = 1, ties = "mean" } = options;
134
+ const { n = 50, f = 0, rule = 1, ties = "mean" } = options;
135
+ const method = approxMethod(options.method);
136
+ const [ruleLeft, ruleRight] = approxRule(rule);
70
137
  const pts = regularize(x, y, ties);
71
138
  const nx = pts.x.length;
72
139
  if (nx <= 1 && method === "linear")
@@ -76,14 +143,16 @@ export function approx(x, y, options = {}) {
76
143
  // As in R, f is checked only for the constant method
77
144
  if (method === "constant" && !(f >= 0 && f <= 1))
78
145
  throw new RangeError("approx(): invalid f value");
79
- const [ruleLeft, ruleRight] = typeof rule === "number" ? [rule, rule] : rule;
80
146
  const yleft = options.yleft ?? (ruleLeft === 1 ? NaN : pts.y[0]);
81
147
  const yright = options.yright ?? (ruleRight === 1 ? NaN : pts.y[nx - 1]);
82
148
  let xout;
83
149
  if (options.xout !== undefined)
84
150
  xout = Array.from(options.xout);
85
151
  else {
86
- if (n <= 0)
152
+ // (NaN and Infinity were an empty result and a JavaScript array error; issue #98)
153
+ if (!Number.isFinite(n) && !Number.isNaN(n))
154
+ throw new RangeError("'length.out' must be a finite number");
155
+ if (!(n > 0))
87
156
  throw new RangeError("'approx' requires n >= 1");
88
157
  xout = seqLength(pts.x[0], pts.x[nx - 1], n);
89
158
  }
@@ -120,7 +189,7 @@ function fmmCoef(x, y) {
120
189
  if (n < 2)
121
190
  return { b, c, d };
122
191
  if (n < 3) {
123
- b[0] = (y[1] - y[0]) / (x[1] - x[0]);
192
+ b[0] = secant(y[0], y[1], x[1] - x[0]);
124
193
  b[1] = b[0];
125
194
  return { b, c, d };
126
195
  }
@@ -273,7 +342,9 @@ function hymanCoef(x, y) {
273
342
  const sm = slope[i === 0 ? 0 : i - 1];
274
343
  const sp = slope[i === n - 1 ? n - 2 : i];
275
344
  const t = Math.min(Math.abs(sm), Math.abs(sp));
276
- const nonneg = sm * sp > 0 ? sp > 0 : b[i] >= 0;
345
+ // the signs compared, not the product sm sp > 0 (the same where it is finite and nonzero): the product of two
346
+ // small secants underflowed to 0 and the fmm slope chose the sign, negative for increasing data (issue #398)
347
+ const nonneg = (sm > 0 && sp > 0) || (sm < 0 && sp < 0) ? sp > 0 : b[i] >= 0;
277
348
  b[i] = nonneg ? Math.min(Math.max(0, b[i]), 3 * t) : Math.max(Math.min(0, b[i]), -3 * t);
278
349
  }
279
350
  for (let i = 0; i < n - 1; i++) {
@@ -287,6 +358,18 @@ function hymanCoef(x, y) {
287
358
  d[n - 1] = d[n - 2];
288
359
  return { b, c, d };
289
360
  }
361
+ /**
362
+ * The exponent k by which the sorted knots are divided when their range overflows (all finite, x_max - x_min
363
+ * infinite), else 0. The spline is then built in x / 2^k, where the spacings are finite, and evaluated at u / 2^k; a
364
+ * derivative of order d is brought back by 2^(-d k) (both exact for normal numbers). R gives 0, NaN or wrong values
365
+ * there (issue #125; spline, review 50).
366
+ */
367
+ function knotScale(x) {
368
+ const n = x.length;
369
+ if (n < 2 || !x.every(Number.isFinite) || Number.isFinite(x[n - 1] - x[0]))
370
+ return 0;
371
+ return Math.floor(Math.log2(maxOf(x.map(Math.abs))));
372
+ }
290
373
  /** Regularized data and coefficients of a b/c/d spline. */
291
374
  function cubicSpline(x, y, method, ties) {
292
375
  const pts = regularize(x, y, ties);
@@ -380,7 +463,11 @@ function evalCubic(sp, xq, deriv0) {
380
463
  */
381
464
  export function spline(x, y, options = {}) {
382
465
  const { method = "fmm", ties = "mean" } = options;
383
- const sp = cubicSpline(x, y, method, ties);
466
+ let sp = cubicSpline(x, y, method, ties);
467
+ // knots whose range overflows (x from -1e308 to 1e308; R gives NaN): the spline in x / 2^k, evaluated at xout / 2^k
468
+ const k = knotScale(sp.x);
469
+ if (k !== 0)
470
+ sp = cubicSpline(Array.from(x, (v) => ldexp(v, -k)), y, method, ties);
384
471
  let xout;
385
472
  if (options.xout !== undefined)
386
473
  xout = Array.from(options.xout);
@@ -388,11 +475,14 @@ export function spline(x, y, options = {}) {
388
475
  // n, xmin and xmax refer to the regularized data
389
476
  const nk = sp.x.length;
390
477
  const n = options.n ?? 3 * nk;
391
- if (n <= 0)
478
+ // (NaN and Infinity were an empty result and a JavaScript array error, as in approx; issue #98)
479
+ if (!Number.isFinite(n))
480
+ throw new RangeError("'length.out' must be a finite number");
481
+ if (!(n > 0))
392
482
  throw new RangeError("'spline' requires n >= 1");
393
- xout = seqLength(options.xmin ?? sp.x[0], options.xmax ?? sp.x[nk - 1], n);
483
+ xout = seqLength(options.xmin ?? ldexp(sp.x[0], k), options.xmax ?? ldexp(sp.x[nk - 1], k), n);
394
484
  }
395
- return { x: xout, y: evalCubic(sp, xout, 0) };
485
+ return { x: xout, y: evalCubic(sp, k === 0 ? xout : xout.map((v) => ldexp(v, -k)), 0) };
396
486
  }
397
487
  /**
398
488
  * The cubic spline through the points, as a function of `x` and the order of derivative (0 to 3; a fraction is
@@ -410,15 +500,27 @@ export function spline(x, y, options = {}) {
410
500
  */
411
501
  export function splinefun(x, y, options = {}) {
412
502
  const { method = "fmm", ties = "mean" } = options;
503
+ // knots whose range overflows: built in x / 2^k (see knotScale), as spline
413
504
  if (method === "monoH.FC") {
414
- const pts = regularize(x, y, ties);
505
+ let pts = regularize(x, y, ties);
415
506
  if (pts.x.length === 0)
416
507
  throw new RangeError("zero non-NA points");
508
+ const k = knotScale(pts.x);
509
+ if (k !== 0)
510
+ pts = regularize(Array.from(x, (v) => ldexp(v, -k)), y, ties);
511
+ // the slopes in units of 1 / 2^k
417
512
  const m = fritschCarlsonSlopes(pts.x, pts.y);
418
- return (xq, deriv = 0) => evalHermite(pts.x, pts.y, m, xq, deriv);
513
+ return (xq, deriv = 0) => evalHermite(pts.x, pts.y, m, k, k, xq, deriv);
419
514
  }
420
- const sp = cubicSpline(x, y, method, ties);
421
- return (xq, deriv = 0) => evalCubic(sp, xq, deriv);
515
+ let sp = cubicSpline(x, y, method, ties);
516
+ const k = knotScale(sp.x);
517
+ if (k === 0)
518
+ return (xq, deriv = 0) => evalCubic(sp, xq, deriv);
519
+ sp = cubicSpline(Array.from(x, (v) => ldexp(v, -k)), y, method, ties);
520
+ return (xq, deriv = 0) => {
521
+ const d = checkDeriv(deriv);
522
+ return evalCubic(sp, Array.from(xq, (v) => ldexp(v, -k)), d).map((v) => ldexp(v, -d * k));
523
+ };
422
524
  }
423
525
  /**
424
526
  * Fritsch and Carlson's (1980) slopes: averages of the neighbouring secants, then, interval by interval from the left,
@@ -429,7 +531,7 @@ function fritschCarlsonSlopes(x, y) {
429
531
  if (n < 2)
430
532
  throw new RangeError("length(m) must be at least two");
431
533
  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));
534
+ const m = Array.from({ length: n }, (_, k) => (k === 0 ? S[0] : k === n - 1 ? S[n - 2] : midpoint(S[k - 1], S[k])));
433
535
  for (let k = 0; k < n - 1; k++) {
434
536
  const Sk = S[k];
435
537
  if (Sk === 0) {
@@ -441,6 +543,25 @@ function fritschCarlsonSlopes(x, y) {
441
543
  const beta = m[k + 1] / Sk;
442
544
  const a = 2 * alpha + beta - 3;
443
545
  const b = alpha + 2 * beta - 3;
546
+ const inRange = Number.isFinite(alpha * (a + b)) && Number.isFinite(a * a) && Number.isFinite(alpha * alpha + beta * beta);
547
+ if (!inRange && Number.isFinite(m[k]) && Number.isFinite(m[k + 1]) && Number.isFinite(Sk)) {
548
+ // only where the ratios or their products overflow (secants 1e-200 and 1e200: beta = Inf, the test Inf < Inf
549
+ // false, and the spline overshot to -6.25e198; issue #397): alpha and beta divided by 2^g, the power of 2 of
550
+ // the larger. The test is homogeneous of degree 2 in (alpha, beta, 3) and the slopes of degree 0
551
+ const ex = (v) => (v === 0 ? -Infinity : Math.floor(Math.log2(Math.abs(v))));
552
+ const g = Math.max(ex(m[k]), ex(m[k + 1])) - ex(Sk);
553
+ const as = scaledProduct([m[k]], [Sk], -g);
554
+ const bs = scaledProduct([m[k + 1]], [Sk], -g);
555
+ const three = ldexpWide(3, -g);
556
+ const a2 = 2 * as + bs - three;
557
+ const b2 = as + 2 * bs - three;
558
+ if (a2 > 0 && b2 > 0 && as * (a2 + b2) < a2 * a2) {
559
+ const tau = (3 * Sk) / Math.sqrt(as * as + bs * bs);
560
+ m[k] = tau * as;
561
+ m[k + 1] = tau * bs;
562
+ }
563
+ continue;
564
+ }
444
565
  if (a > 0 && b > 0 && alpha * (a + b) < a * a) {
445
566
  const tau = (3 * Sk) / Math.sqrt(alpha * alpha + beta * beta);
446
567
  m[k] = tau * alpha;
@@ -449,13 +570,19 @@ function fritschCarlsonSlopes(x, y) {
449
570
  }
450
571
  return m;
451
572
  }
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) {
573
+ /**
574
+ * Evaluates the cubic Hermite spline (or a derivative) with values y and slopes at x; linear outside the data. The
575
+ * 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
576
+ * formula): splinefunH keeps the given slopes (e = 0), monoH.FC its slopes in the divided coordinate (e = k), so that
577
+ * neither is rescaled where it could overflow or lose bits.
578
+ */
579
+ function evalHermite(x, y, m, k, e, xq, deriv0) {
454
580
  const deriv = checkDeriv(deriv0);
455
581
  const n = x.length;
456
- return Array.from(xq, (u) => {
457
- if (Number.isNaN(u))
582
+ return Array.from(xq, (u0) => {
583
+ if (Number.isNaN(u0))
458
584
  return NaN;
585
+ const u = k === 0 ? u0 : ldexp(u0, -k);
459
586
  // i = number of knots <= u
460
587
  let lo = 0;
461
588
  let hi = n;
@@ -468,8 +595,8 @@ function evalHermite(x, y, m, xq, deriv0) {
468
595
  }
469
596
  const i = lo;
470
597
  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;
598
+ const j = i === 0 ? 0 : n - 1;
599
+ return deriv === 0 ? y[j] + ldexp(m[j] * (u - x[j]), k - e) : deriv === 1 ? ldexp(m[j], -e) : 0;
473
600
  }
474
601
  const x0 = x[i - 1];
475
602
  const h = x[i] - x0;
@@ -479,15 +606,48 @@ function evalHermite(x, y, m, xq, deriv0) {
479
606
  const y1 = y[i];
480
607
  const m0 = m[i - 1];
481
608
  const m1 = m[i];
482
- const delta = (y1 - y0) / h;
609
+ // the secant in the units of the slopes
610
+ const delta = ldexp(secant(y0, y1, h), e - k);
483
611
  switch (deriv) {
484
612
  case 0: {
613
+ // h m_i in the original units
485
614
  const h01 = t * t * (3 - 2 * t);
486
- return y0 * (1 - h01) + h * m0 * (t * t1 * t1) + y1 * h01 + h * m1 * (t * t * t1);
615
+ // a term whose h m overflows before the small basis factor (h = 1e200, m = 1e200 at t = 1e-100 gave
616
+ // Inf - Inf for 1e300; issue #400): the product of the three factors with their exponents apart
617
+ const term = (mi, b) => {
618
+ const v = ldexp(h * mi, k - e) * b;
619
+ return Number.isFinite(v) || !Number.isFinite(mi) || !Number.isFinite(b) ? v : scaledProduct([h, mi, b], [], k - e);
620
+ };
621
+ return y0 * (1 - h01) + term(m0, t * t1 * t1) + y1 * h01 + term(m1, t * t * t1);
622
+ }
623
+ case 1: {
624
+ if (Number.isFinite(delta) || !Number.isFinite(y0) || !Number.isFinite(y1)) {
625
+ return ldexp(delta * (-6 * t * t1) + m0 * (t1 * (3 * t - 1)) + m1 * (t * (3 * t - 2)), -e);
626
+ }
627
+ // the secant overflows before the small basis factor (y1 - y0 = 1e200 over h = 1e-200 at t = 1e-100 gave
628
+ // Inf for 6e300; issue #401): (y1 - y0) times the factor over h with the exponents apart, in the original units
629
+ const dy = y1 - y0;
630
+ const d = Number.isFinite(dy) ? scaledProduct([dy, -6 * t * t1], [h], -k) : scaledProduct([y1 / 2 - y0 / 2, -6 * t * t1], [h], 1 - k);
631
+ return d + ldexp(m0 * (t1 * (3 * t - 1)) + m1 * (t * (3 * t - 2)), -e);
632
+ }
633
+ case 2: {
634
+ if (Number.isFinite(delta) || !Number.isFinite(y0) || !Number.isFinite(y1)) {
635
+ return ldexp((delta * (6 - 12 * t) + m0 * (6 * t - 4) + m1 * (6 * t - 2)) / h, -e - k);
636
+ }
637
+ // the secant overflows before the small basis factor (y1 - y0 = 1e200 over h = 1e-200 at t = 1/2 gave
638
+ // Inf * 0 = NaN for 0, R too; issue #466): as the first derivative (#401), (y1 - y0) times the factor over h^2
639
+ const dy = y1 - y0;
640
+ 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);
641
+ return d + ldexp((m0 * (6 * t - 4) + m1 * (6 * t - 2)) / h, -e - k);
642
+ }
643
+ default: {
644
+ const num = -12 * delta + 6 * m0 + 6 * m1;
645
+ const hh = h * h;
646
+ // h^2 outside the normal range (h = 1e200: num / Inf was 0 for 1.2e-199; issue #399): divided by h twice
647
+ if (!(hh >= 2 ** -1022 && hh < Infinity))
648
+ return ldexp(num / h / h, -e - 2 * k);
649
+ return ldexp(num / hh, -e - 2 * k);
487
650
  }
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
651
  }
492
652
  });
493
653
  }
@@ -515,7 +675,10 @@ export function splinefunH(x, y, m) {
515
675
  for (let i = 1; i < n; i++)
516
676
  if (!(X[i] - X[i - 1] > 0))
517
677
  throw new RangeError("'x' must be *strictly* increasing (non - NA)");
518
- return (xq, deriv = 0) => evalHermite(X, Y, M, xq, deriv);
678
+ // knots whose range overflows: x / 2^k (see knotScale), the slopes as given
679
+ const k = knotScale(X);
680
+ const Xs = k === 0 ? X : X.map((v) => ldexp(v, -k));
681
+ return (xq, deriv = 0) => evalHermite(Xs, Y, M, k, 0, xq, deriv);
519
682
  }
520
683
  /**
521
684
  * Lagrange interpolation in barycentric form through the points (xi, yi). Equivalent to `pracma::barylag()` in R.
@@ -535,17 +698,83 @@ export function barylag(xi, yi, x) {
535
698
  if (Y.length !== n)
536
699
  throw new RangeError("'xi' and 'yi' must have the same length");
537
700
  const xs = Array.from(x);
538
- const lo = Math.min(...X);
539
- const hi = Math.max(...X);
701
+ const lo = minOf(X);
702
+ const hi = maxOf(X);
540
703
  if (xs.some((v) => v < lo || v > hi))
541
704
  throw new RangeError("Some interpolation points outside the nodes.");
542
- const w = X.map((a, j) => {
705
+ // finite nodes whose range overflows: the weights and differences in x / 2, where every difference is finite (the
706
+ // barycentric ratio does not change with the scale of x). barylag([-1e308, 1e308], [-1, 1], [0]) was NaN (issue #215)
707
+ const half = Number.isFinite(lo) && Number.isFinite(hi) && !Number.isFinite(hi - lo);
708
+ const Xc = half ? X.map((a) => a / 2) : X;
709
+ // 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
710
+ // common power of 2 (which leaves the interpolant unchanged): the products of nodes of 1e200 overflowed and every
711
+ // weight was 0, the result NaN (pracma's too; issue #14). Without renormalisation the weights are as before
712
+ const parts = Xc.map((a, j) => {
543
713
  let p = 1;
544
- for (let k = 0; k < n; k++)
545
- if (k !== j)
546
- p *= a - X[k];
547
- return 1 / p;
714
+ let e = 0;
715
+ for (let k = 0; k < n; k++) {
716
+ if (k === j)
717
+ continue;
718
+ const d = a - Xc[k];
719
+ const q = p * d;
720
+ if (p !== 0 && d !== 0 && Number.isFinite(d) && !(Math.abs(q) >= 2 ** -1022 && Math.abs(q) < Infinity)) {
721
+ // only where the product leaves the normal range (it underflowed to 0 before the check below: nodes 0,
722
+ // 2^-250, 2^-249, 2^-600 gave the weight 1/0 and NaN; issue #402): both factors as m 2^f, multiplied exactly
723
+ const fp = Math.floor(Math.log2(Math.abs(p)));
724
+ const fd = Math.floor(Math.log2(Math.abs(d)));
725
+ p = ldexp(p, -fp) * ldexp(d, -fd);
726
+ e += fp + fd;
727
+ continue;
728
+ }
729
+ p = q;
730
+ const m = Math.abs(p);
731
+ if (m > 2 ** 500 || (m < 2 ** -500 && m > 0)) {
732
+ const f = Math.floor(Math.log2(m));
733
+ p = ldexp(p, -f);
734
+ e += f;
735
+ }
736
+ }
737
+ return { p, e };
548
738
  });
739
+ const shift = parts.reduce((s, q) => Math.max(s, -q.e), -Infinity);
740
+ const w = parts.map((q) => ldexp(1 / q.p, -q.e - shift));
741
+ const finiteData = X.every(Number.isFinite) && Y.every(Number.isFinite);
742
+ // power of 2 of the largest |y_j|, so that the sum of the first form below does not overflow
743
+ const yTop = finiteData ? Y.reduce((s, y) => (y === 0 ? s : Math.max(s, Math.floor(Math.log2(Math.abs(y))))), -Infinity) : 0;
744
+ // 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:
745
+ // 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
746
+ // of the largest |y_j|. undefined where a difference is 0 (u a node after halving)
747
+ const firstForm = (u) => {
748
+ if (yTop === -Infinity)
749
+ return 0;
750
+ let lm = 1;
751
+ let le = 0;
752
+ const terms = [];
753
+ for (let j = 0; j < n; j++) {
754
+ const d = u - Xc[j];
755
+ if (d === 0)
756
+ return undefined;
757
+ const f = Math.floor(Math.log2(Math.abs(d)));
758
+ const dm = ldexp(d, -f);
759
+ lm *= dm;
760
+ const g = Math.floor(Math.log2(Math.abs(lm)));
761
+ lm = ldexp(lm, -g);
762
+ le += f + g;
763
+ const r = 1 / parts[j].p / dm;
764
+ if (!Number.isFinite(r) || r === 0)
765
+ return undefined;
766
+ const fr = Math.floor(Math.log2(Math.abs(r)));
767
+ terms.push({ r: ldexp(r, -fr), x: fr - parts[j].e - f });
768
+ }
769
+ const top = terms.reduce((s, q) => Math.max(s, q.x), -Infinity);
770
+ let s = 0;
771
+ for (let j = 0; j < n; j++)
772
+ s += ldexp(terms[j].r, terms[j].x - top) * ldexp(Y[j], -yTop);
773
+ if (s === 0)
774
+ return 0;
775
+ const fs = Math.floor(Math.log2(Math.abs(s)));
776
+ return ldexpWide(lm * ldexp(s, -fs), le + top + yTop + fs);
777
+ };
549
778
  return xs.map((v) => {
550
779
  let num = 0;
551
780
  let den = 0;
@@ -553,13 +782,53 @@ export function barylag(xi, yi, x) {
553
782
  const at = X.lastIndexOf(v);
554
783
  if (at >= 0)
555
784
  return Y[at];
785
+ let sumAbs = 0;
786
+ let sumAbsNum = 0;
556
787
  for (let j = 0; j < n; j++) {
557
- const diff = v - X[j];
788
+ const diff = (half ? v / 2 : v) - Xc[j];
558
789
  const t = w[j] / diff;
559
790
  num += t * Y[j];
560
791
  den += t;
792
+ sumAbs += Math.abs(t);
793
+ sumAbsNum += Math.abs(t * Y[j]);
794
+ }
795
+ const r = num / den;
796
+ // The denominator lost to cancellation while the numerator did not: a rounded sum of the t_j is not below 2^-53
797
+ // of the largest |t_j| unless large terms cancelled exactly, leaving only terms below their rounding error. The
798
+ // 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
799
+ // Infinity for 2^-300 (pracma NaN; issue #467). There the first form l(x) sum w_j y_j / (x - x_j) (no cancelling
800
+ // denominator). Data whose numerator cancels too (a constant) keep the second form, which reproduces them
801
+ if (finiteData &&
802
+ Number.isFinite(sumAbs) &&
803
+ sumAbs > 0 &&
804
+ Math.abs(den) < ldexp(sumAbs, -100) &&
805
+ Number.isFinite(sumAbsNum) &&
806
+ Math.abs(num) >= ldexp(sumAbsNum, -26)) {
807
+ const first = firstForm(half ? v / 2 : v);
808
+ if (first !== undefined)
809
+ return first;
561
810
  }
562
- return num / den;
811
+ if (Number.isFinite(r) || !finiteData)
812
+ return r;
813
+ // only where the plain quotient is not finite for finite data: w_j / (x - x_j) overflowed (the nodes 0, 2^-250,
814
+ // 2^-249, 2^-600 at 2^-1074 gave Inf / Inf; issue #402). The terms from the products m 2^e and the differences as
815
+ // m 2^f, divided by the power of 2 of the largest term (which leaves the quotient unchanged)
816
+ const terms = parts.map((q, j) => {
817
+ const diff = (half ? v / 2 : v) - Xc[j];
818
+ const f = Math.floor(Math.log2(Math.abs(diff)));
819
+ return { r: 1 / q.p / ldexp(diff, -f), x: -q.e - f };
820
+ });
821
+ if (!terms.every((q) => Number.isFinite(q.r) && Number.isFinite(q.x)))
822
+ return r;
823
+ const top = terms.reduce((s, q) => Math.max(s, q.x), -Infinity);
824
+ let num2 = 0;
825
+ let den2 = 0;
826
+ for (let j = 0; j < n; j++) {
827
+ const t = ldexp(terms[j].r, terms[j].x - top);
828
+ num2 += t * Y[j];
829
+ den2 += t;
830
+ }
831
+ return num2 / den2;
563
832
  });
564
833
  }
565
834
  /**
@@ -582,9 +851,40 @@ export function hermiteInterp(xi, yi, di, x) {
582
851
  const n = X.length;
583
852
  if (Y.length !== n || D.length !== n)
584
853
  throw new RangeError("'xi', 'yi' and 'di' must have the same length");
585
- const z = X.flatMap((v) => [v, v]);
854
+ // the divided differences of order j scale as 1 / x^j: for large nodes they underflow (hermiteInterp([-1e200, 1e200],
855
+ // [-1, 1], [0, 0], [0.5e200]) was -1 for 0.6875, issue #216 follow-up), for tiny ones they overflow, and where the
856
+ // range of finite nodes overflows the separations are infinite and the quotients 0 (hermiteInterp([-1e308, 1e308],
857
+ // [-1, 1], [0, 0], [0]) was -1, issue #216). Only then (a quotient of finite, nonzero numbers that is not finite or
858
+ // below the normal range, or a range that overflows), the polynomial in x / 2^k with 2^k near the largest node
859
+ // (derivatives times 2^k, exact), where the nodes are of order 1. Otherwise the same bits as the unscaled table.
860
+ let k0 = knotScale([...X].sort((a, b) => a - b));
861
+ let table = k0 === 0 ? hermiteTable(X, Y, D) : undefined;
862
+ if (table?.lost && [X, Y, D].every((v) => v.every(Number.isFinite))) {
863
+ const k = Math.floor(Math.log2(maxOf(X.map(Math.abs))));
864
+ if (k !== 0)
865
+ [k0, table] = [k, undefined];
866
+ }
867
+ if (table === undefined)
868
+ table = hermiteTable(X.map((v) => ldexp(v, -k0)), Y, D.map((v) => ldexp(v, k0)));
869
+ const { z, coef } = table;
586
870
  const m = 2 * n;
587
- // divided-difference table, column by column (in place)
871
+ return Array.from(x, (v) => {
872
+ let r = coef[m - 1];
873
+ const u = k0 === 0 ? v : ldexp(v, -k0);
874
+ for (let k = m - 2; k >= 0; k--)
875
+ r = r * (u - z[k]) + coef[k];
876
+ return r;
877
+ });
878
+ }
879
+ /**
880
+ * The divided-difference table of hermiteInterp on the doubled nodes; `lost` where a quotient of finite, nonzero
881
+ * numbers is not finite or falls below the normal range.
882
+ */
883
+ function hermiteTable(X, Y, D) {
884
+ const z = X.flatMap((v) => [v, v]);
885
+ const m = z.length;
886
+ let lost = false;
887
+ // divided-difference table, column by column
588
888
  const q = Y.flatMap((v) => [v, v]);
589
889
  const coef = [q[0]];
590
890
  let col = q.slice();
@@ -593,16 +893,18 @@ export function hermiteInterp(xi, yi, di, x) {
593
893
  for (let i = 0; i < m - k; i++) {
594
894
  if (k === 1 && z[i + 1] === z[i])
595
895
  next.push(D[i >> 1]);
596
- else
597
- next.push((col[i + 1] - col[i]) / (z[i + k] - z[i]));
896
+ else {
897
+ const num = col[i + 1] - col[i];
898
+ const den = z[i + k] - z[i];
899
+ const r = secant(col[i], col[i + 1], den);
900
+ const finite = Number.isFinite(col[i + 1]) && Number.isFinite(col[i]);
901
+ if (finite && num !== 0 && den !== 0 && !(Math.abs(r) >= 2 ** -1022 && Math.abs(r) < Infinity))
902
+ lost = true;
903
+ next.push(r);
904
+ }
598
905
  }
599
906
  coef.push(next[0]);
600
907
  col = next;
601
908
  }
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
- });
909
+ return { z, coef, lost };
608
910
  }
@@ -25,6 +25,10 @@ export function ode(y, times, func, parms = [], options = {}) {
25
25
  const method = options.method ?? "rk4";
26
26
  if (method !== "euler" && method !== "rk2" && method !== "rk4")
27
27
  throw new RangeError(`unknown method '${String(method)}'`);
28
+ // an infinite or NaN time gives an infinite or NaN step, and the state became NaN even with a zero derivative
29
+ // (Infinity * 0) (#360)
30
+ if (!times.every(Number.isFinite))
31
+ throw new RangeError("'times' must be finite values");
28
32
  const p = [...parms];
29
33
  const n = y.length;
30
34
  const deriv = (t, s) => {
@@ -42,6 +46,11 @@ export function ode(y, times, func, parms = [], options = {}) {
42
46
  for (let j = 1; j < times.length; j++) {
43
47
  const t = times[j - 1];
44
48
  const h = times[j] - t;
49
+ if (!Number.isFinite(h) && Number.isFinite(t) && Number.isFinite(times[j])) {
50
+ state = halvedStep(state, t, times[j] / 2 - t / 2, method, deriv);
51
+ out.push([times[j], ...state]);
52
+ continue;
53
+ }
45
54
  const k1 = deriv(t, state);
46
55
  if (method === "euler")
47
56
  state = axpy(state, h, k1);
@@ -53,9 +62,54 @@ export function ode(y, times, func, parms = [], options = {}) {
53
62
  const k2 = deriv(t + h / 2, axpy(state, h / 2, k1));
54
63
  const k3 = deriv(t + h / 2, axpy(state, h / 2, k2));
55
64
  const k4 = deriv(t + h, axpy(state, h, k3));
56
- state = state.map((v, i) => v + (h / 6) * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]));
65
+ // h/6 times the weighted sum, as deSolve. Where h/6 falls below the normal range or the sum overflows (2 k2 for a
66
+ // slope near the largest double), the sum divided by 4 (exact weights, no overflow), times h (a small h first
67
+ // brought into the normal range by 2^60, exactly), over 1.5: ode([0], [0, MIN], () => [1]) stayed at 0, and a
68
+ // slope of 1e308 over h = 1e-308 gave Infinity for 1 (issue #124)
69
+ const h6 = h / 6;
70
+ const plain = h === 0 || Math.abs(h6) >= 2 ** -1022;
71
+ const scale = Math.abs(h) < 1 ? 2 ** 60 : 1;
72
+ state = state.map((v, i) => {
73
+ const inc = h6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]);
74
+ if (plain && Number.isFinite(inc))
75
+ return v + inc;
76
+ const quarter = k1[i] / 4 + k2[i] / 2 + k3[i] / 2 + k4[i] / 4;
77
+ const scaled = h * scale * quarter;
78
+ // the quarter-weighted sum itself overflows for finite slopes (weights summing to 1.5: ode([0], [0, 0.5], () =>
79
+ // [1.7e308]) was Infinity for 8.5e307, #469): the sum divided by 8, 2 h eighth / 1.5
80
+ if (!Number.isFinite(quarter) && [k1[i], k2[i], k3[i], k4[i]].every(Number.isFinite)) {
81
+ const eighth = k1[i] / 8 + k2[i] / 4 + k3[i] / 4 + k4[i] / 8;
82
+ return v + 2 * ((h * eighth) / 1.5);
83
+ }
84
+ if (Number.isFinite(scaled) || !Number.isFinite(quarter))
85
+ return v + scaled / 1.5 / scale;
86
+ // the scaled product overflows for a large slope (ode([0], [0, 0.5], () => [1e308]) was Infinity for 5e307,
87
+ // #394): there h quarter is far above the normal range and needs no scale; where it overflows too, with h / 2
88
+ const p = h * quarter;
89
+ return v + (Number.isFinite(p) ? p / 1.5 : 2 * (((h / 2) * quarter) / 1.5));
90
+ });
57
91
  }
58
92
  out.push([times[j], ...state]);
59
93
  }
60
94
  return out;
61
95
  }
96
+ // One step whose length h = 2 hh overflows although both times are finite (ode(y, c(-1e308, 1e308), ...)): the same
97
+ // formulas with h k formed as hh k added twice, so a zero slope keeps the state (1 + Inf * 0 was NaN, issue #211). The
98
+ // stage times are t + hh and (t + hh) + hh, the midpoint and the end.
99
+ function halvedStep(state, t, hh, method, deriv) {
100
+ const twice = (s, c, k) => s.map((v, i) => v + c * k[i] + c * k[i]);
101
+ const mid = t + hh;
102
+ const end = mid + hh;
103
+ const k1 = deriv(t, state);
104
+ if (method === "euler")
105
+ return twice(state, hh, k1);
106
+ if (method === "rk2") {
107
+ const k2 = deriv(end, twice(state, hh, k1));
108
+ return twice(state, hh, k1.map((v, i) => 0.5 * v + 0.5 * k2[i]));
109
+ }
110
+ const k2 = deriv(mid, state.map((v, i) => v + hh * k1[i]));
111
+ const k3 = deriv(mid, state.map((v, i) => v + hh * k2[i]));
112
+ const k4 = deriv(end, twice(state, hh, k3));
113
+ // h/6 (k1 + 2 k2 + 2 k3 + k4) = (hh / 1.5) times the quarter-weighted sum, added twice
114
+ return twice(state, hh / 1.5, k1.map((v, i) => v / 4 + k2[i] / 2 + k3[i] / 2 + k4[i] / 4));
115
+ }