@numero-uno-jpn/rstats 0.15.0 → 0.15.2

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 (81) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.ja.md +8 -8
  3. package/README.md +8 -8
  4. package/dist/chunks/chunk-2CUKVVRO.js +2 -0
  5. package/dist/chunks/{chunk-4XGKAHD3.js → chunk-3WQCKGKP.js} +2 -2
  6. package/dist/chunks/{chunk-7XHAE2LG.js → chunk-4Z2XDWKV.js} +1 -1
  7. package/dist/chunks/{chunk-QQIWOGHR.js → chunk-AJBLCNZ7.js} +2 -2
  8. package/dist/chunks/chunk-D4F7GQAY.js +2 -0
  9. package/dist/chunks/chunk-EBQMGCQZ.js +2 -0
  10. package/dist/chunks/{chunk-WEWXYHPR.js → chunk-HBMHR5SS.js} +2 -2
  11. package/dist/chunks/{chunk-HS7KIFMR.js → chunk-IBPWRQIF.js} +2 -2
  12. package/dist/chunks/chunk-JLAH3X77.js +2 -0
  13. package/dist/chunks/chunk-LG74QY5U.js +2 -0
  14. package/dist/chunks/{chunk-A3XZUJCP.js → chunk-PEYGUK32.js} +2 -2
  15. package/dist/chunks/{chunk-HNLKOICT.js → chunk-PWVQVJTP.js} +1 -1
  16. package/dist/chunks/{chunk-AEFWSUZ2.js → chunk-Q4PGYESP.js} +2 -2
  17. package/dist/chunks/{chunk-GZTLODPK.js → chunk-RCAL4VHM.js} +2 -2
  18. package/dist/chunks/{chunk-XMTYTJT6.js → chunk-SREPSVTT.js} +2 -2
  19. package/dist/chunks/chunk-UFT662QZ.js +2 -0
  20. package/dist/chunks/{chunk-CJ5ETQCK.js → chunk-VWJ74UHC.js} +2 -2
  21. package/dist/chunks/{chunk-VAPGDPHM.js → chunk-XNPU54NH.js} +1 -1
  22. package/dist/chunks/{chunk-PRDF6IU6.js → chunk-XPLDEK6D.js} +2 -2
  23. package/dist/chunks/{chunk-LWUTCYTZ.js → chunk-YGT4P7EU.js} +1 -1
  24. package/dist/chunks/{chunk-7GEYDIQC.js → chunk-YVREYVI2.js} +2 -2
  25. package/dist/descriptive.js +2 -2
  26. package/dist/distributions/arcsine.js +48 -4
  27. package/dist/distributions/beta.d.ts +1 -1
  28. package/dist/distributions/beta.js +64 -1
  29. package/dist/distributions/exponential.js +11 -2
  30. package/dist/distributions/f.js +104 -21
  31. package/dist/distributions/gamma.d.ts +13 -2
  32. package/dist/distributions/gamma.js +91 -12
  33. package/dist/distributions/geometric.js +16 -3
  34. package/dist/distributions/invgamma.js +56 -10
  35. package/dist/distributions/kumaraswamy.js +98 -17
  36. package/dist/distributions/lognormal.js +28 -4
  37. package/dist/distributions/nbeta.js +540 -37
  38. package/dist/distributions/nchisq.d.ts +25 -0
  39. package/dist/distributions/nchisq.js +396 -60
  40. package/dist/distributions/negbinomial.js +20 -5
  41. package/dist/distributions/normal.js +3 -0
  42. package/dist/distributions/nt.js +263 -51
  43. package/dist/distributions/pareto.js +68 -19
  44. package/dist/distributions/signrank.js +73 -20
  45. package/dist/distributions/t.js +48 -10
  46. package/dist/distributions/triangular.js +66 -27
  47. package/dist/distributions/tukey.js +94 -50
  48. package/dist/distributions/uniform.js +12 -9
  49. package/dist/distributions/weibull.js +43 -8
  50. package/dist/distributions.js +2 -2
  51. package/dist/internal/ddexp.d.ts +5 -0
  52. package/dist/internal/ddexp.js +28 -3
  53. package/dist/internal/discrete.js +30 -7
  54. package/dist/internal/invert.js +49 -0
  55. package/dist/internal/noncentral.d.ts +34 -0
  56. package/dist/internal/noncentral.js +115 -2
  57. package/dist/internal/poissonMixture.d.ts +7 -2
  58. package/dist/internal/poissonMixture.js +113 -32
  59. package/dist/linalg.js +2 -2
  60. package/dist/mixed.js +2 -2
  61. package/dist/numerics.js +2 -2
  62. package/dist/rstats.js +14 -14
  63. package/dist/special/dd.d.ts +1 -1
  64. package/dist/special/dd.js +4 -1
  65. package/dist/special/igam.js +93 -15
  66. package/dist/special/incbet.d.ts +10 -0
  67. package/dist/special/incbet.js +154 -48
  68. package/dist/special/incbetLargeA.js +47 -13
  69. package/dist/special/incbetPrefactor.d.ts +52 -0
  70. package/dist/special/incbetPrefactor.js +92 -0
  71. package/dist/special/incbetTemme.js +15 -3
  72. package/dist/special/loader.js +33 -7
  73. package/dist/special.js +2 -2
  74. package/dist/tests.js +2 -2
  75. package/package.json +1 -1
  76. package/dist/chunks/chunk-4EOKNOXP.js +0 -2
  77. package/dist/chunks/chunk-CMPDE3SZ.js +0 -2
  78. package/dist/chunks/chunk-LU5FHU2O.js +0 -2
  79. package/dist/chunks/chunk-LVXAWWUX.js +0 -2
  80. package/dist/chunks/chunk-NYGWVZOC.js +0 -2
  81. package/dist/chunks/chunk-VSKWQMSG.js +0 -2
@@ -16,13 +16,23 @@ const SCALE_STEP = -900;
16
16
  /**
17
17
  * Tables are cached per n (so that quantile searches, or alternating calls with different n, do not rebuild them).
18
18
  * When the total number of entries exceeds CACHE_BUDGET, the oldest are evicted (at most 32 MB in two Float64Arrays).
19
+ * The key is n for the main table and -n for the low table of n (tableValue), so both share the budget.
19
20
  */
20
21
  const cache = new Map();
21
22
  const CACHE_BUDGET = 2 ** 21;
22
23
  let cached = 0;
23
24
  /** Maximum table length (computations needing more throw RangeError; about 512 MB in two Float64Arrays) */
24
25
  const MAX_LEN = 2 ** 25;
25
- /** Build the table of counts for s = 0..J (J at most the end of the lower half, floor(n(n+1)/4)) */
26
+ /**
27
+ * Build the table of counts for s = 0..J (J at most the end of the lower half, floor(n(n+1)/4)).
28
+ *
29
+ * Rescaling by 2^-900 makes the low entries subnormal or 0: each loses up to 2^-1075 (in units of the new scale).
30
+ * What an entry s' holds after element k reaches the final w[s] through the elements k+1..kmax, as many times as
31
+ * there are subsets of them summing to s - s', so the loss reaches w[s] at most 2^(kmax - k) times over. A count at
32
+ * s therefore keeps relative accuracy 2^-60 if c_n(s) >= 2^(S - 1075 + kmax - k + 60) for every rescaling (to scale
33
+ * S after element k); that bound is minTrusted. Being below the smallest normal number is not enough: for n = 2000
34
+ * the entries around s = 95000 lost digits (relative 1e-7) through the entries below them that were lost.
35
+ */
26
36
  function buildTable(n, J) {
27
37
  if (J + 1 > MAX_LEN) {
28
38
  throw new RangeError(`signrank: n = ${n} needs too large a table (${J + 1} entries)`);
@@ -30,6 +40,8 @@ function buildTable(n, J) {
30
40
  const w = new Float64Array(J + 1);
31
41
  w[0] = 1;
32
42
  let scale = 0;
43
+ // log2 of the smallest trusted true count (see above)
44
+ let trustLog2 = -Infinity;
33
45
  // Elements k > J do not contribute to sums s <= J
34
46
  const kmax = Math.min(n, J);
35
47
  for (let k = 1; k <= kmax; k++) {
@@ -42,6 +54,7 @@ function buildTable(n, J) {
42
54
  for (let s = 0; s <= J; s++)
43
55
  w[s] *= f;
44
56
  scale -= SCALE_STEP;
57
+ trustLog2 = Math.max(trustLog2, scale - 1015 + kmax - k);
45
58
  }
46
59
  }
47
60
  // Cumulative sum (with Kahan compensation)
@@ -55,35 +68,60 @@ function buildTable(n, J) {
55
68
  hi = t;
56
69
  cum[s] = hi;
57
70
  }
58
- return { n, len: J + 1, count: w, cum, scale };
71
+ return { n, len: J + 1, count: w, cum, scale, minTrusted: 2 ** (trustLog2 - scale) };
59
72
  }
60
- /** Return a table for n usable for s <= J */
61
- function table(n, J) {
62
- const old = cache.get(n);
73
+ /** Return a table for n usable for s <= J (with low, the low table of n; see lowValue) */
74
+ function table(n, J, low = false) {
75
+ const key = low ? -n : n;
76
+ const old = cache.get(key);
63
77
  if (old !== undefined && old.len > J) {
64
78
  // Move to the end as most recently used
65
- cache.delete(n);
66
- cache.set(n, old);
79
+ cache.delete(key);
80
+ cache.set(key, old);
67
81
  return old;
68
82
  }
69
83
  const half = Math.floor((n * (n + 1)) / 4);
70
84
  // Growing a little at a time would cause repeated rebuilds, so double the size
71
85
  const want = Math.min(half, Math.max(J, old === undefined ? 0 : 2 * old.len));
72
- const t = buildTable(n, want);
86
+ return store(key, buildTable(n, want), old);
87
+ }
88
+ /** Put t in the cache under key (replacing old) and evict the oldest tables beyond the budget */
89
+ function store(key, t, old) {
73
90
  if (old !== undefined) {
74
- cache.delete(n);
91
+ cache.delete(key);
75
92
  cached -= old.len;
76
93
  }
77
- cache.set(n, t);
94
+ cache.set(key, t);
78
95
  cached += t.len;
79
- for (const [key, v] of cache) {
80
- if (cached <= CACHE_BUDGET || key === n)
96
+ for (const [k, v] of cache) {
97
+ if (cached <= CACHE_BUDGET || k === key)
81
98
  break;
82
- cache.delete(key);
99
+ cache.delete(k);
83
100
  cached -= v.len;
84
101
  }
85
102
  return t;
86
103
  }
104
+ /**
105
+ * The value at s of the count (cum false) or cumulative count (cum true) for n, with the table it is scaled by.
106
+ * A table built far beyond s has been rescaled for its large entries, and its low entries have lost digits (c_n(0) = 1
107
+ * becomes 2^-1800 for n = 2000 and underflows), so a value the bound of buildTable does not cover is read from the
108
+ * low table of n instead, built only as far as needed. A table built up to J = s is exact at s: s is its largest
109
+ * entry, and rescaling keeps the largest entry at least 1 (every count c_n(s) for 0 <= s <= n(n+1)/2 is at least 1).
110
+ */
111
+ function tableValue(n, s, cum) {
112
+ const trusted = (t, v) => s === t.len - 1 || v >= (cum ? (s + 1) * t.minTrusted : t.minTrusted);
113
+ let t = table(n, s);
114
+ let v = (cum ? t.cum : t.count)[s];
115
+ if (trusted(t, v))
116
+ return [v, t];
117
+ t = table(n, s, true);
118
+ v = (cum ? t.cum : t.count)[s];
119
+ if (trusted(t, v))
120
+ return [v, t];
121
+ // The low table (grown by doubling) was rescaled too far for s: rebuild it exactly up to s
122
+ t = store(-n, buildTable(n, s), cache.get(-n));
123
+ return [(cum ? t.cum : t.count)[s], t];
124
+ }
87
125
  /** Convert the table value v (scale 2^-scale) to the probability v 2^(scale - n) (underflow only at the final step) */
88
126
  function toProb(v, t, log) {
89
127
  const e = t.scale - t.n;
@@ -92,7 +130,22 @@ function toProb(v, t, log) {
92
130
  if (!log)
93
131
  return p;
94
132
  // log(v) + e log 2 loses digits since both terms are large, so use log(p) if the probability is a normal number
95
- return p >= 1e-300 ? Math.log(p) : Math.log(v) + e * Math.LN2;
133
+ if (p >= 1e-300)
134
+ return Math.log(p);
135
+ // Otherwise split v into its significand m in [1, 2) and exponent, so that the result does not depend on the
136
+ // scale of the table (the same count read from tables of different scale gives the same bits)
137
+ let k = Math.floor(Math.log2(v));
138
+ const k1 = Math.trunc(k / 2);
139
+ let m = v * 2 ** -k1 * 2 ** -(k - k1);
140
+ if (m >= 2) {
141
+ m /= 2;
142
+ k++;
143
+ }
144
+ else if (m < 1) {
145
+ m *= 2;
146
+ k--;
147
+ }
148
+ return Math.log(m) + (k + e) * Math.LN2;
96
149
  }
97
150
  /** Check and round n. NaN if invalid */
98
151
  function signrankN(n) {
@@ -114,8 +167,8 @@ export function dsignrank1(x, n, log) {
114
167
  if (x < 0 || x > total)
115
168
  return d0(log);
116
169
  const s = Math.min(x, total - x);
117
- const t = table(n, s);
118
- return toProb(t.count[s], t, log);
170
+ const [v, t] = tableValue(n, s, false);
171
+ return toProb(v, t, log);
119
172
  }
120
173
  /** P[V <= x] (lower) / P[V > x] (0 <= x < total, x an integer) */
121
174
  function psignrankRaw(x, n, lowerTail, logP) {
@@ -127,11 +180,11 @@ function psignrankRaw(x, n, lowerTail, logP) {
127
180
  const direct = lowerTail ? lowerIdx : upperIdx;
128
181
  const other = lowerTail ? upperIdx : lowerIdx;
129
182
  if (direct <= other) {
130
- const t = table(n, direct);
131
- return toProb(t.cum[direct], t, logP);
183
+ const [c, t] = tableValue(n, direct, true);
184
+ return toProb(c, t, logP);
132
185
  }
133
- const t = table(n, other);
134
- const v = toProb(t.cum[other], t, false);
186
+ const [c, t] = tableValue(n, other, true);
187
+ const v = toProb(c, t, false);
135
188
  return logP ? Math.log1p(-v) : 1 - v;
136
189
  }
137
190
  export function psignrank1(q, n, lowerTail, logP) {
@@ -70,8 +70,43 @@ export function dtDensity1(x, df, log) {
70
70
  }
71
71
  return dtCore(x, df, log);
72
72
  }
73
+ /** Below this n the upper tail is 1/2 - tinyDfDelta (the next terms are under 1e-23 absolute) */
74
+ const TINY_DF = 1e-15;
75
+ /**
76
+ * P[0 < T < t] (t > 0) for n < TINY_DF: (n/2) asinh(t / sqrt(n)). With a = n/2 and y = t^2/(n + t^2),
77
+ * P[|T| < t] = I_y(1/2, a), where 1/B(1/2, a) = a (1 + O(a)) and the integrand u^(-1/2) (1 - u)^(a-1) is
78
+ * u^(-1/2) / (1 - u) (1 + O(a log(1 - u))), whose integral over [0, y] is 2 atanh(sqrt(y)) = 2 asinh(t / sqrt(n)).
79
+ * The relative error is O(n log(t^2/n)), below n^2 log^2(t^2/n) < 1e-23 absolute. The incomplete beta function's
80
+ * series loses digits for so small an a (pt(-5.05, 2.4e-242) was 0.49999999999998995, 0.5 further out)
81
+ */
82
+ function tinyDfDelta(t, n) {
83
+ const r = t / Math.sqrt(n);
84
+ // asinh(r) = log(2 r) + O(r^-2) where r overflows
85
+ return 0.5 * n * (r < 1e300 ? Math.asinh(r) : Math.LN2 + Math.log(t) - 0.5 * Math.log(n));
86
+ }
87
+ /**
88
+ * x = n/(n + t^2) and 1 - x = t^2/(n + t^2) in double-double. Where t^2 or n is beyond the range of Veltkamp
89
+ * splitting (the products in ddDiv overflowed to NaN: pt(-3.5e151, 4.3e121)), both are first scaled by the same power
90
+ * of 2, 2^-2m with 2^m >= max(t, sqrt(n)) (exact unless t^2 / n is so small that 1 - x does not matter)
91
+ */
92
+ function betaArgs(t, n) {
93
+ let tt = t;
94
+ let nn = n;
95
+ if (t > 1e150 || n > 1e290) {
96
+ const f = 2 ** -Math.ceil(Math.log2(Math.max(t, Math.sqrt(n))));
97
+ tt = t * f;
98
+ nn = n * f * f;
99
+ }
100
+ const t2d = twoProd(tt, tt);
101
+ const den = ddAdd(t2d, [nn, 0]);
102
+ return [ddDiv([nn, 0], den), ddDiv(t2d, den)];
103
+ }
73
104
  /** Log or value of P[T > t] (t > 0): half of s = P[|T| > t] = I_{n/(n+t^2)}(n/2, 1/2) */
74
105
  function upperTailPositive(t, n, log) {
106
+ if (n < TINY_DF) {
107
+ const d = tinyDfDelta(t, n);
108
+ return log ? Math.log1p(-2 * d) - Math.LN2 : 0.5 - d;
109
+ }
75
110
  const t2 = t * t;
76
111
  const x = n / (n + t2);
77
112
  if (!(x > 1e-250)) {
@@ -82,14 +117,14 @@ function upperTailPositive(t, n, log) {
82
117
  const e = ddAdd(ddMulNum(lx, n / 2), [-Math.log(n / 2) - lbeta(n / 2, 0.5) - Math.LN2, 0]);
83
118
  return log ? e[0] + e[1] : Math.exp(e[0]) * (1 + e[1]);
84
119
  }
85
- // Form x = n/(n + t^2) and 1 - x = t^2/(n + t^2) in double-double
86
- const t2d = twoProd(t, t);
87
- const den = ddAdd(t2d, [n, 0]);
88
- const s = betaIncDD(n / 2, 0.5, ddDiv([n, 0], den), ddDiv(t2d, den), true, log);
120
+ const [x1, y1] = betaArgs(t, n);
121
+ const s = betaIncDD(n / 2, 0.5, x1, y1, true, log);
89
122
  return log ? s - Math.LN2 : s / 2;
90
123
  }
91
124
  /** [log, linear] of upperTailPositive (each value identical to upperTailPositive) */
92
125
  function upperTailPositiveBoth(t, n) {
126
+ if (n < TINY_DF)
127
+ return [upperTailPositive(t, n, true), upperTailPositive(t, n, false)];
93
128
  const t2 = t * t;
94
129
  const x = n / (n + t2);
95
130
  if (!(x > 1e-250)) {
@@ -97,9 +132,8 @@ function upperTailPositiveBoth(t, n) {
97
132
  const e = ddAdd(ddMulNum(lx, n / 2), [-Math.log(n / 2) - lbeta(n / 2, 0.5) - Math.LN2, 0]);
98
133
  return [e[0] + e[1], Math.exp(e[0]) * (1 + e[1])];
99
134
  }
100
- const t2d = twoProd(t, t);
101
- const den = ddAdd(t2d, [n, 0]);
102
- const s = betaIncBothDD(n / 2, 0.5, ddDiv([n, 0], den), ddDiv(t2d, den), true);
135
+ const [x1, y1] = betaArgs(t, n);
136
+ const s = betaIncBothDD(n / 2, 0.5, x1, y1, true);
103
137
  return [s[0] - Math.LN2, s[1] / 2];
104
138
  }
105
139
  export function pt1(q, df, lowerTail, logP) {
@@ -140,10 +174,14 @@ export function qt1(p, df, lowerTail, logP) {
140
174
  let x0;
141
175
  // log t from the tail asymptotic P[T > t] ≈ n^(n/2) t^(-n) / (n B(n/2, 1/2))
142
176
  const lx0 = (0.5 * n * Math.log(n) - Math.log(n) - lbeta(n / 2, 0.5) - logTarget) / n;
143
- // ±Inf if the answer exceeds the largest double (t is large there and the asymptotic form is accurate)
144
- if (lx0 > 709.78)
177
+ // ±Inf if the answer exceeds the largest double (t is large there and the asymptotic form is accurate); near that
178
+ // decided by the tail at the largest double itself (a fixed 709.78 gave -Infinity for qt(3.048e-196, 0.633), whose
179
+ // answer is -1.79e308)
180
+ if (lx0 > 709.79 || (lx0 > 709.77 && upperTailPositive(Number.MAX_VALUE, n, true) > logTarget))
145
181
  return lower ? -Infinity : Infinity;
146
- if (logTarget < -30) {
182
+ // The asymptotic form needs t^2 >> n; for large n the tail stays normal-like far out (t^2 < n), where it would
183
+ // start Newton near sqrt(n) (qt(1.6e-243, 1e120) converged to -1.13 from there)
184
+ if (logTarget < -30 && 2 * lx0 > Math.log(n) + 1) {
147
185
  x0 = Math.exp(lx0);
148
186
  }
149
187
  else {
@@ -3,25 +3,46 @@
3
3
  // Written for rStats.js (no ported code). With w = b - a:
4
4
  // f(x) = 2 (x - a) / (w (c - a)) left of c, 2 (b - x) / (w (b - c)) right of it;
5
5
  // P[X <= x] = (x - a)^2 / (w (c - a)) left of c, P[X > x] = (b - x)^2 / (w (b - c)) right of it.
6
- // Each tail is computed from its own end, and the quantile from the tail it falls in.
6
+ // Each tail is computed from its own end, and the quantile from the tail it falls in. Products are formed from ratios
7
+ // of lengths (each at most 1), so that wide and narrow intervals neither overflow nor underflow on the way.
7
8
  import { vectorize } from "../internal/vectorize.js";
8
9
  import { d0, dt0, dt1, quantileBoundaries } from "../internal/dpq.js";
9
10
  const valid = (a, b, c) => Number.isFinite(a) && Number.isFinite(b) && a < b && a <= c && c <= b;
11
+ /** 1/2 when b - a overflows (x, a, b and c are all halved then; the probabilities do not change), else 1 */
12
+ const halfIfOverflow = (a, b) => (Number.isFinite(b - a) ? 1 : 0.5);
10
13
  export function dtriang1(x, a, b, c, log) {
11
14
  if (Number.isNaN(x) || !valid(a, b, c))
12
15
  return NaN;
13
16
  if (x < a || x > b)
14
17
  return d0(log);
18
+ const h = halfIfOverflow(a, b);
19
+ if (h !== 1) {
20
+ const d = dtriang1(x * h, a * h, b * h, c * h, log);
21
+ return log ? d + Math.log(h) : d * h;
22
+ }
15
23
  const w = b - a;
16
- if (x === c)
17
- return log ? Math.log(2 / w) : 2 / w;
18
- // the density is (2 / w) (1 - r), r the fraction of the way from the mode to the end on x's side; near the mode
19
- // 1 - r from r (x - c is exact there), elsewhere from the distance to the end
20
- const r = x < c ? (c - x) / (c - a) : (x - c) / (b - c);
24
+ // The density is (2 / w) s with s = (x - a) / (c - a) left of the mode, (b - x) / (b - c) right of it (s <= 1, so
25
+ // nothing over- or underflows on the way unless the density itself does). Near the mode s = 1 - r with r the
26
+ // fraction of the way from the mode to the end on x's side (x - c is exact there)
27
+ const r = x === c ? 0 : x < c ? (c - x) / (c - a) : (x - c) / (b - c);
21
28
  if (r < 0.5)
22
- return log ? Math.log(2 / w) + Math.log1p(-r) : (2 / w) * (1 - r);
23
- const d = x < c ? (2 * (x - a)) / (w * (c - a)) : (2 * (b - x)) / (w * (b - c));
24
- return log ? Math.log(d) : d;
29
+ return log ? Math.LN2 - Math.log(w) + Math.log1p(-r) : (2 * (1 - r)) / w;
30
+ const s = x < c ? (x - a) / (c - a) : (b - x) / (b - c);
31
+ return log ? Math.LN2 - Math.log(w) + Math.log(s) : (2 * s) / w;
32
+ }
33
+ /**
34
+ * The tails [lower, upper] at a < q < b (b - a finite), from ratios of lengths that are at most 1, and the log of the
35
+ * near tail (the one from the end on q's side of the mode) as a sum of logs, which stays exact where the tail is subnormal
36
+ */
37
+ function tails(q, a, b, c) {
38
+ const w = b - a;
39
+ // the far tail as a sum of positive terms: 1 - (q - a)^2 / (w (c - a)) = (b - c) / w + (c - q)(q - a + c - a) / (w (c - a))
40
+ if (q <= c) {
41
+ const [s, t] = [(q - a) / (c - a), (q - a) / w];
42
+ return [s * t, (b - c) / w + ((c - q) / (c - a)) * (t + (c - a) / w), Math.log(s) + Math.log(t)];
43
+ }
44
+ const [s, t] = [(b - q) / (b - c), (b - q) / w];
45
+ return [(c - a) / w + ((q - c) / (b - c)) * (t + (b - c) / w), s * t, Math.log(s) + Math.log(t)];
25
46
  }
26
47
  export function ptriang1(q, a, b, c, lowerTail, logP) {
27
48
  if (Number.isNaN(q) || !valid(a, b, c))
@@ -30,23 +51,16 @@ export function ptriang1(q, a, b, c, lowerTail, logP) {
30
51
  return dt0(lowerTail, logP);
31
52
  if (q >= b)
32
53
  return dt1(lowerTail, logP);
33
- const w = b - a;
34
- // the far tail as a sum of positive terms: 1 - (q - a)^2 / (w (c - a)) = (b - c) / w + (c - q)(q + c - 2a) / (w (c - a))
35
- let lower;
36
- let upper;
37
- if (q <= c) {
38
- lower = ((q - a) * (q - a)) / (w * (c - a));
39
- upper = (b - c) / w + ((c - q) * (q - a + (c - a))) / (w * (c - a));
40
- }
41
- else {
42
- upper = ((b - q) * (b - q)) / (w * (b - c));
43
- lower = (c - a) / w + ((q - c) * (b - q + (b - c))) / (w * (b - c));
44
- }
45
- const v = lowerTail ? lower : upper;
54
+ const h = halfIfOverflow(a, b);
55
+ const [lower, upper, lnear] = tails(q * h, a * h, b * h, c * h);
56
+ // The sum of positive terms can round an ulp above 1
57
+ const v = Math.min(lowerTail ? lower : upper, 1);
46
58
  if (!logP)
47
59
  return v;
48
- // the log of a probability above 1/2 from the other tail
49
- return v > 0.5 ? Math.log1p(-(lowerTail ? upper : lower)) : Math.log(v);
60
+ // the log of a probability above 1/2 from the other tail; a subnormal near tail from its factors
61
+ if (v > 0.5)
62
+ return Math.log1p(-(lowerTail ? upper : lower));
63
+ return v < 2 ** -1022 && lowerTail === q <= c ? lnear : Math.log(v);
50
64
  }
51
65
  export function qtriang1(p, a, b, c, lowerTail, logP) {
52
66
  if (Number.isNaN(p) || !valid(a, b, c))
@@ -54,13 +68,38 @@ export function qtriang1(p, a, b, c, lowerTail, logP) {
54
68
  const bd = quantileBoundaries(p, a, b, lowerTail, logP);
55
69
  if (bd !== undefined)
56
70
  return bd;
71
+ const h = halfIfOverflow(a, b);
72
+ if (h !== 1)
73
+ return qtriang1(p, a * h, b * h, c * h, lowerTail, logP) / h;
57
74
  const w = b - a;
58
75
  const pv = logP ? Math.exp(p) : p;
76
+ // sqrt of the tail on the side of p; exp(p / 2) where exp(p) is subnormal
77
+ const sqrtP = logP && pv < 2 ** -1022 ? Math.exp(p / 2) : Math.sqrt(pv);
59
78
  const lower = lowerTail ? pv : logP ? -Math.expm1(p) : 1 - p;
60
79
  const upper = lowerTail ? (logP ? -Math.expm1(p) : 1 - p) : pv;
61
- if (lower <= (c - a) / w)
62
- return a + Math.sqrt(lower * w * (c - a));
63
- return b - Math.sqrt(upper * w * (b - c));
80
+ // Left of the mode x - a = (c - a) sqrt(t) with t = lower w / (c - a), the share of the left part's probability;
81
+ // right of it b - x = (b - c) sqrt(t), t = upper w / (b - c). Near the mode (t > 1/2) the distance from it instead,
82
+ // (1 - sqrt(t)) = (1 - t) / (1 + sqrt(t)) with 1 - t from the other tail (for c = a or c = b that tail itself, so
83
+ // no cancellation near the end). The square roots are taken factor by factor so that no product over- or underflows
84
+ const cl = (c - a) / w;
85
+ const cr = (b - c) / w;
86
+ let x;
87
+ if (cl > 0 && lower <= cl) {
88
+ const t = (lower / (c - a)) * w;
89
+ x =
90
+ t <= 0.5
91
+ ? a + (lowerTail ? sqrtP : Math.sqrt(lower)) * Math.sqrt(w) * Math.sqrt(c - a)
92
+ : c - ((c - a) * ((upper - cr) / cl)) / (1 + Math.sqrt(t));
93
+ }
94
+ else {
95
+ const t = (upper / (b - c)) * w;
96
+ x =
97
+ t <= 0.5
98
+ ? b - (lowerTail ? Math.sqrt(upper) : sqrtP) * Math.sqrt(w) * Math.sqrt(b - c)
99
+ : c + ((b - c) * ((lower - cl) / cr)) / (1 + Math.sqrt(t));
100
+ }
101
+ // Rounding must not take x out of the support
102
+ return Math.min(Math.max(x, a), b);
64
103
  }
65
104
  /**
66
105
  * Density of the triangular distribution. Equivalent to `extraDistr::dtriang(x, a = -1, b = 1, c = (a + b)/2, log = FALSE)` in R.