@ac-kit/math-linear 0.2.1 → 0.4.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 (178) hide show
  1. package/CHANGELOG.md +337 -0
  2. package/README.md +232 -16
  3. package/dist/_brand.d.ts +14 -0
  4. package/dist/_brand.d.ts.map +1 -0
  5. package/dist/_brand.js +2 -0
  6. package/dist/_brand.js.map +1 -0
  7. package/dist/_invert.d.ts +214 -0
  8. package/dist/_invert.d.ts.map +1 -0
  9. package/dist/_invert.js +884 -0
  10. package/dist/_invert.js.map +1 -0
  11. package/dist/_slerp.d.ts +29 -0
  12. package/dist/_slerp.d.ts.map +1 -1
  13. package/dist/_slerp.js +103 -0
  14. package/dist/_slerp.js.map +1 -1
  15. package/dist/_strided-range.d.ts +23 -0
  16. package/dist/_strided-range.d.ts.map +1 -0
  17. package/dist/_strided-range.js +75 -0
  18. package/dist/_strided-range.js.map +1 -0
  19. package/dist/_trs.d.ts +38 -0
  20. package/dist/_trs.d.ts.map +1 -0
  21. package/dist/_trs.js +132 -0
  22. package/dist/_trs.js.map +1 -0
  23. package/dist/affine2-array.d.ts +53 -0
  24. package/dist/affine2-array.d.ts.map +1 -0
  25. package/dist/affine2-array.js +107 -0
  26. package/dist/affine2-array.js.map +1 -0
  27. package/dist/affine2-componentwise.d.ts +28 -0
  28. package/dist/affine2-componentwise.d.ts.map +1 -0
  29. package/dist/affine2-componentwise.js +66 -0
  30. package/dist/affine2-componentwise.js.map +1 -0
  31. package/dist/affine2.d.ts +156 -0
  32. package/dist/affine2.d.ts.map +1 -0
  33. package/dist/affine2.js +437 -0
  34. package/dist/affine2.js.map +1 -0
  35. package/dist/affine3-array.d.ts +53 -0
  36. package/dist/affine3-array.d.ts.map +1 -0
  37. package/dist/affine3-array.js +137 -0
  38. package/dist/affine3-array.js.map +1 -0
  39. package/dist/affine3-componentwise.d.ts +32 -0
  40. package/dist/affine3-componentwise.d.ts.map +1 -0
  41. package/dist/affine3-componentwise.js +100 -0
  42. package/dist/affine3-componentwise.js.map +1 -0
  43. package/dist/affine3.d.ts +205 -0
  44. package/dist/affine3.d.ts.map +1 -0
  45. package/dist/affine3.js +792 -0
  46. package/dist/affine3.js.map +1 -0
  47. package/dist/checked/index.d.ts +35 -0
  48. package/dist/checked/index.d.ts.map +1 -0
  49. package/dist/checked/index.js +58 -0
  50. package/dist/checked/index.js.map +1 -0
  51. package/dist/euler.d.ts +65 -0
  52. package/dist/euler.d.ts.map +1 -0
  53. package/dist/euler.js +217 -0
  54. package/dist/euler.js.map +1 -0
  55. package/dist/index.d.ts +29 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +29 -0
  58. package/dist/index.js.map +1 -1
  59. package/dist/kl-activations.d.ts.map +1 -1
  60. package/dist/kl-activations.js +4 -3
  61. package/dist/kl-activations.js.map +1 -1
  62. package/dist/mat2x2-array.d.ts +36 -0
  63. package/dist/mat2x2-array.d.ts.map +1 -0
  64. package/dist/mat2x2-array.js +71 -0
  65. package/dist/mat2x2-array.js.map +1 -0
  66. package/dist/mat2x2-componentwise.d.ts +86 -0
  67. package/dist/mat2x2-componentwise.d.ts.map +1 -0
  68. package/dist/mat2x2-componentwise.js +199 -0
  69. package/dist/mat2x2-componentwise.js.map +1 -0
  70. package/dist/mat2x2.d.ts +79 -25
  71. package/dist/mat2x2.d.ts.map +1 -1
  72. package/dist/mat2x2.js +192 -93
  73. package/dist/mat2x2.js.map +1 -1
  74. package/dist/mat3x3-array.d.ts +36 -0
  75. package/dist/mat3x3-array.d.ts.map +1 -0
  76. package/dist/mat3x3-array.js +91 -0
  77. package/dist/mat3x3-array.js.map +1 -0
  78. package/dist/mat3x3-componentwise.d.ts +86 -0
  79. package/dist/mat3x3-componentwise.d.ts.map +1 -0
  80. package/dist/mat3x3-componentwise.js +299 -0
  81. package/dist/mat3x3-componentwise.js.map +1 -0
  82. package/dist/mat3x3.d.ts +153 -48
  83. package/dist/mat3x3.d.ts.map +1 -1
  84. package/dist/mat3x3.js +470 -192
  85. package/dist/mat3x3.js.map +1 -1
  86. package/dist/mat4x4-array.d.ts +46 -0
  87. package/dist/mat4x4-array.d.ts.map +1 -0
  88. package/dist/mat4x4-array.js +133 -0
  89. package/dist/mat4x4-array.js.map +1 -0
  90. package/dist/mat4x4-componentwise.d.ts +87 -0
  91. package/dist/mat4x4-componentwise.d.ts.map +1 -0
  92. package/dist/mat4x4-componentwise.js +434 -0
  93. package/dist/mat4x4-componentwise.js.map +1 -0
  94. package/dist/mat4x4.d.ts +221 -67
  95. package/dist/mat4x4.d.ts.map +1 -1
  96. package/dist/mat4x4.js +972 -334
  97. package/dist/mat4x4.js.map +1 -1
  98. package/dist/projection.d.ts +113 -0
  99. package/dist/projection.d.ts.map +1 -0
  100. package/dist/projection.js +418 -0
  101. package/dist/projection.js.map +1 -0
  102. package/dist/quaternion-array.d.ts +47 -0
  103. package/dist/quaternion-array.d.ts.map +1 -0
  104. package/dist/quaternion-array.js +86 -0
  105. package/dist/quaternion-array.js.map +1 -0
  106. package/dist/quaternion.d.ts +106 -22
  107. package/dist/quaternion.d.ts.map +1 -1
  108. package/dist/quaternion.js +253 -182
  109. package/dist/quaternion.js.map +1 -1
  110. package/dist/transform.d.ts +220 -0
  111. package/dist/transform.d.ts.map +1 -0
  112. package/dist/transform.js +412 -0
  113. package/dist/transform.js.map +1 -0
  114. package/dist/tridiagonal.d.ts +52 -0
  115. package/dist/tridiagonal.d.ts.map +1 -0
  116. package/dist/tridiagonal.js +90 -0
  117. package/dist/tridiagonal.js.map +1 -0
  118. package/dist/upload.d.ts +55 -0
  119. package/dist/upload.d.ts.map +1 -0
  120. package/dist/upload.js +129 -0
  121. package/dist/upload.js.map +1 -0
  122. package/dist/vec2-array-componentwise.d.ts +207 -0
  123. package/dist/vec2-array-componentwise.d.ts.map +1 -0
  124. package/dist/vec2-array-componentwise.js +472 -0
  125. package/dist/vec2-array-componentwise.js.map +1 -0
  126. package/dist/vec2-array.d.ts +53 -0
  127. package/dist/vec2-array.d.ts.map +1 -0
  128. package/dist/vec2-array.js +123 -0
  129. package/dist/vec2-array.js.map +1 -0
  130. package/dist/vec2-componentwise.d.ts +311 -0
  131. package/dist/vec2-componentwise.d.ts.map +1 -0
  132. package/dist/vec2-componentwise.js +542 -0
  133. package/dist/vec2-componentwise.js.map +1 -0
  134. package/dist/vec2.d.ts +97 -82
  135. package/dist/vec2.d.ts.map +1 -1
  136. package/dist/vec2.js +121 -216
  137. package/dist/vec2.js.map +1 -1
  138. package/dist/vec3-array-componentwise.d.ts +207 -0
  139. package/dist/vec3-array-componentwise.d.ts.map +1 -0
  140. package/dist/vec3-array-componentwise.js +510 -0
  141. package/dist/vec3-array-componentwise.js.map +1 -0
  142. package/dist/vec3-array.d.ts +102 -0
  143. package/dist/vec3-array.d.ts.map +1 -0
  144. package/dist/vec3-array.js +299 -0
  145. package/dist/vec3-array.js.map +1 -0
  146. package/dist/vec3-componentwise.d.ts +310 -0
  147. package/dist/vec3-componentwise.d.ts.map +1 -0
  148. package/dist/vec3-componentwise.js +594 -0
  149. package/dist/vec3-componentwise.js.map +1 -0
  150. package/dist/vec3.d.ts +177 -87
  151. package/dist/vec3.d.ts.map +1 -1
  152. package/dist/vec3.js +391 -272
  153. package/dist/vec3.js.map +1 -1
  154. package/dist/vec4-array-componentwise.d.ts +198 -0
  155. package/dist/vec4-array-componentwise.d.ts.map +1 -0
  156. package/dist/vec4-array-componentwise.js +521 -0
  157. package/dist/vec4-array-componentwise.js.map +1 -0
  158. package/dist/vec4-array.d.ts +12 -0
  159. package/dist/vec4-array.d.ts.map +1 -0
  160. package/dist/vec4-array.js +43 -0
  161. package/dist/vec4-array.js.map +1 -0
  162. package/dist/vec4-componentwise.d.ts +299 -0
  163. package/dist/vec4-componentwise.d.ts.map +1 -0
  164. package/dist/vec4-componentwise.js +637 -0
  165. package/dist/vec4-componentwise.js.map +1 -0
  166. package/dist/vec4.d.ts +59 -53
  167. package/dist/vec4.d.ts.map +1 -1
  168. package/dist/vec4.js +74 -249
  169. package/dist/vec4.js.map +1 -1
  170. package/dist/view-basis.d.ts +15 -0
  171. package/dist/view-basis.d.ts.map +1 -0
  172. package/dist/view-basis.js +29 -0
  173. package/dist/view-basis.js.map +1 -0
  174. package/dist/viewport.d.ts +114 -0
  175. package/dist/viewport.d.ts.map +1 -0
  176. package/dist/viewport.js +250 -0
  177. package/dist/viewport.js.map +1 -0
  178. package/package.json +19 -9
@@ -0,0 +1,884 @@
1
+ import { binaryExponent, float64ToParts, ratioToFloat64, scaleByPowerOfTwoInPlace, } from "@ac-kit/core";
2
+ import { dotExactInto, twoProductErrorInRange, twoSumError, } from "@ac-kit/math-scalar";
3
+ /**
4
+ * The row and column exponents of {@link equilibrateForInversion_}, kept for
5
+ * {@link unequilibrateInverse_}: the rows in `[0, size)`, the columns in
6
+ * `[size, 2 · size)`. One inversion at a time, no callback inside it.
7
+ */
8
+ const EXPONENTS_ = new Int32Array(8);
9
+ /**
10
+ * Whether the last {@link equilibrateForInversion_} rounded an entry: scaled
11
+ * into the subnormal range or below it, an entry loses digits or vanishes, and
12
+ * the scaled matrix is then no longer exactly `diag(2^-r) · m · diag(2^-c)`.
13
+ */
14
+ let isEquilibrationLossy_ = false;
15
+ /**
16
+ * `binaryExponent(values[index])`, for a finite non-zero entry: called with an
17
+ * array and an integer, so no double crosses a call the engine may not inline,
18
+ * where it would be boxed; `binaryExponent`, a few bit operations, is inlined
19
+ * into it. The exponent is a small integer, returned unboxed.
20
+ */
21
+ function exponentAt_(values, index) {
22
+ return binaryExponent(values[index]);
23
+ }
24
+ /** The entry {@link equilibrateForInversion_} checks for a rounded scaling. */
25
+ const ROUND_TRIP_ = new Float64Array(1);
26
+ /** Below every exponent `binaryExponent` gives for a non-zero number. */
27
+ const NO_EXPONENT_ = -100000;
28
+ /**
29
+ * The second chance of a matrix inversion. A matrix whose entries span a range
30
+ * that the cofactors' products cannot (`diag(1e200, 1e200, 1e200, 1e-200)`: a
31
+ * determinant of `1e400`, an inverse of `1e-200` and `1e200`) is inverted in
32
+ * the scale where they do. Writes `m`, a square matrix of `size` rows in any
33
+ * layout, into `out` as `diag(2^-r) · m · diag(2^-c)` (exact: powers of two,
34
+ * unless an entry lands in or below the subnormal range, see below), where
35
+ * `2^r` of a row is the power of two at or below its largest entry and `2^c` of
36
+ * a column that of the same after the rows, so every row and column has an
37
+ * entry of magnitude in `[1/2, 2)`. The caller inverts `out` and passes the
38
+ * result to {@link unequilibrateInverse_}, which scales each entry of the
39
+ * inverse by its own power of two in one step, so no entry passes through a
40
+ * range its neighbours do not share. Returns `false`, writing nothing, when an
41
+ * entry is not finite or a row or a column is zero, which no scaling helps.
42
+ * When the entries of a column span more than the binary64 range once their
43
+ * rows are scaled (`[[2^900, 2^900, 0], [2^900, 2^900, 2^-200], [0, 2^900,
44
+ * 2^900]]`, whose `2^-200` becomes `2^-1100`), an entry rounds or vanishes, and
45
+ * {@link isEquilibrationLossy_} says so. `out` may be `m`.
46
+ */
47
+ export function equilibrateForInversion_(out, m, size) {
48
+ // Zeros are skipped rather than measured: their exponent, `-Infinity`, is a
49
+ // double, which a call the engine does not inline returns boxed.
50
+ for (let row = 0; row < size; row++) {
51
+ let exponent = NO_EXPONENT_;
52
+ for (let column = 0; column < size; column++) {
53
+ const value = m[row * size + column];
54
+ if (value - value !== 0) {
55
+ return false;
56
+ }
57
+ if (value !== 0) {
58
+ exponent = Math.max(exponent, exponentAt_(m, row * size + column));
59
+ }
60
+ }
61
+ if (exponent === NO_EXPONENT_) {
62
+ return false;
63
+ }
64
+ EXPONENTS_[row] = exponent;
65
+ }
66
+ // The exponents are adjusted, not the entries scaled and measured: an entry
67
+ // that the row scaling alone sends below the subnormal range still counts.
68
+ for (let column = 0; column < size; column++) {
69
+ let exponent = NO_EXPONENT_;
70
+ for (let row = 0; row < size; row++) {
71
+ if (m[row * size + column] !== 0) {
72
+ exponent = Math.max(exponent, exponentAt_(m, row * size + column) - EXPONENTS_[row]);
73
+ }
74
+ }
75
+ if (exponent === NO_EXPONENT_) {
76
+ return false;
77
+ }
78
+ EXPONENTS_[size + column] = exponent;
79
+ }
80
+ isEquilibrationLossy_ = false;
81
+ for (let row = 0; row < size; row++) {
82
+ for (let column = 0; column < size; column++) {
83
+ const index = row * size + column;
84
+ const value = m[index];
85
+ out[index] = value;
86
+ if (value !== 0) {
87
+ // `0 - r - c`: `-r - c` is the double -0 when both are 0, and a
88
+ // call boxes it.
89
+ const exponent = 0 - EXPONENTS_[row] - EXPONENTS_[size + column];
90
+ scaleByPowerOfTwoInPlace(out, index, exponent);
91
+ // Only a result in or below the subnormal range can round; scaled
92
+ // back, an exact one is the entry again.
93
+ if (out[index] === 0 || exponentAt_(out, index) < -1022) {
94
+ ROUND_TRIP_[0] = out[index];
95
+ scaleByPowerOfTwoInPlace(ROUND_TRIP_, 0, 0 - exponent);
96
+ isEquilibrationLossy_ ||= ROUND_TRIP_[0] !== value;
97
+ }
98
+ }
99
+ }
100
+ }
101
+ return true;
102
+ }
103
+ /**
104
+ * Turns the inverse in `out` of the equilibrated matrix of
105
+ * {@link equilibrateForInversion_} into the inverse of the original, in place:
106
+ * its entry at row `i` and column `j` is scaled by `2^(-c_i - r_j)`. `path`,
107
+ * {@link COFACTOR_PATH_} or {@link PIVOTED_PATH_}, says which inversion wrote
108
+ * it, so how far its entries may be from the exact ones, as a fraction of the
109
+ * largest of them ({@link ERROR_SHARES_}). Returns whether every entry, plus
110
+ * its error so scaled, stays within `Number.MAX_VALUE`: only then is the exact
111
+ * inverse sure to round to finite numbers. A rounded entry just below the limit
112
+ * may stand for one past it (`1 / (4237 · 2^-1024)` rounded, times `4237`, is
113
+ * `Number.MAX_VALUE`, where the exact `2^1024` rounds to `Infinity`), and an
114
+ * entry rounded to zero may stand for one the scaling sends past it. `false`
115
+ * leaves `out` partly scaled.
116
+ */
117
+ export function unequilibrateInverse_(out, size, path) {
118
+ const count = size * size;
119
+ let largest = 0;
120
+ for (let index = 0; index < count; index++) {
121
+ largest = Math.max(largest, Math.abs(out[index]));
122
+ }
123
+ const error = ERROR_SHARES_[path] * largest;
124
+ for (let row = 0; row < size; row++) {
125
+ for (let column = 0; column < size; column++) {
126
+ const index = row * size + column;
127
+ const exponent = 0 - EXPONENTS_[size + row] - EXPONENTS_[column];
128
+ // The rounding of this sum is far inside the slack of `share`.
129
+ REACH_[0] = Math.abs(out[index]) + error;
130
+ scaleByPowerOfTwoInPlace(REACH_, 0, exponent);
131
+ if (!(REACH_[0] <= Number.MAX_VALUE)) {
132
+ return false;
133
+ }
134
+ if (out[index] !== 0) {
135
+ scaleByPowerOfTwoInPlace(out, index, exponent);
136
+ }
137
+ }
138
+ }
139
+ return true;
140
+ }
141
+ /** How far an entry of {@link unequilibrateInverse_} may reach, scaled back. */
142
+ const REACH_ = new Float64Array(1);
143
+ /**
144
+ * The largest magnitude the binary64 paths of an inversion accept for an entry
145
+ * of their inverse (or of an affine inverse's translation): their error bounds,
146
+ * at most about `2^-39` of the largest entry, keep the exact entry below
147
+ * `Number.MAX_VALUE`, so that it rounds to a finite number. An entry at or past
148
+ * it is left to {@link invertRescaled_}, whose bound is checked entry by entry
149
+ * and whose overlap with the overflow threshold exact arithmetic settles.
150
+ */
151
+ export const INVERSE_LIMIT_ = Number.MAX_VALUE * (1 - 2 ** -30);
152
+ /**
153
+ * The error of an entry of an inverse, as a fraction of its largest entry, by
154
+ * path. {@link COFACTOR_PATH_}: a cofactor expansion accepted under
155
+ * {@link INVERSE_TOLERANCE_} (the cofactors within `2^-41 / 3` of the largest,
156
+ * the determinant within `2^-41` of itself, two roundings: about `2^-40`), or
157
+ * the 2 × 2 one, within a few units in the last place; rounded up to `2^-36`.
158
+ * {@link PIVOTED_PATH_}: {@link invertPivoted_}, each column `x` of whose
159
+ * certified inverse solves `(m + Δ) · x = e` with `|Δ| ≤ γ₃ₙ · |L| · |U|`
160
+ * (Higham, theorem 9.4), so lies within `‖X‖∞ · γ₃ₙ · ‖|L| · |U|‖∞ / (1 − …)`
161
+ * of the exact one relative to `‖x‖∞`, at most about `3 · 2^-10` under
162
+ * {@link PIVOTED_MARGIN_} (`γ₃ₙ` at most three times the `γ` it checks), and
163
+ * `‖x‖∞` is at most the largest entry; rounded up to `2^-6`.
164
+ */
165
+ const ERROR_SHARES_ = Float64Array.of(2 ** -36, 2 ** -6);
166
+ const COFACTOR_PATH_ = 0;
167
+ const PIVOTED_PATH_ = 1;
168
+ /**
169
+ * The equilibrated matrix of {@link invertRescaled_}, then its inverse: a
170
+ * `number[]` of double elements from the start, like the matrices the kernels
171
+ * it is passed to otherwise see (one container type per parameter).
172
+ */
173
+ const EQUILIBRATED_ = Array.from({ length: 16 }, () => 0.5);
174
+ /**
175
+ * The second chance of a matrix inversion, after its plain cofactor expansion
176
+ * failed. Inverts `m`, a square matrix of `size` rows (at most 4) in any
177
+ * layout, into `out` and returns `true`, or fills `out` with `NaN` and returns
178
+ * `false` exactly when `m` is singular, an entry is not finite, or an entry of
179
+ * the inverse, rounded to the nearest binary64, is beyond `Number.MAX_VALUE`.
180
+ * `out` may be `m`.
181
+ *
182
+ * The rows and columns are scaled by powers of two first
183
+ * ({@link equilibrateForInversion_}), and the inverse scaled back
184
+ * ({@link unequilibrateInverse_}). `invert` (writing only on success, its
185
+ * output may be its input) inverts the equilibrated matrix; when it refuses, LU
186
+ * factorisation with partial pivoting ({@link invertPivoted_}) does, which no
187
+ * cancellation of the cofactors stops. When `decisive`, a refusal of `invert`
188
+ * already means the equilibrated matrix, so `m`, is singular. Otherwise an
189
+ * exact elimination proves it singular or invertible. When the elimination
190
+ * rounded, when the inverse it found leaves the binary64 range once scaled
191
+ * back, or when the scaling itself rounded an entry (an entry far below the
192
+ * others of its column, which it sends below the subnormal range, so that the
193
+ * scaled matrix is no longer exactly `m` scaled, and may be singular when `m`
194
+ * is not), {@link invertExact_} settles `m` itself: `false` is never a rounding
195
+ * artefact. A scaling that rounded skips `invert` and the decisive shortcut,
196
+ * and the elimination counts it in its certificate. A zero row or column, or an
197
+ * entry that is not finite, is refused before any of them.
198
+ *
199
+ * Time complexity: O(size³), with no allocation unless the exact settlement
200
+ * runs: for a matrix whose determinant rounding takes to zero in both its
201
+ * cofactors and its rounded elimination, one with a condition number beyond
202
+ * about `2^52`, singular or not; for an inverse whose scaled-back entries
203
+ * overflow, or come within their error bound of overflowing; and for a matrix
204
+ * whose scaling rounded an entry and whose elimination cannot certify its
205
+ * inverse.
206
+ */
207
+ export function invertRescaled_(out, m, size, invert, decisive) {
208
+ const count = size * size;
209
+ if (equilibrateForInversion_(EQUILIBRATED_, m, size)) {
210
+ // A scaling that rounded an entry gives a matrix that is not `m`
211
+ // scaled, and the scaling back, by powers beyond the binary64 range,
212
+ // magnifies the difference in any entry: only exact arithmetic answers.
213
+ let path = COFACTOR_PATH_;
214
+ let outcome = PIVOTED_UNSETTLED_;
215
+ if (!isEquilibrationLossy_) {
216
+ if (invert(EQUILIBRATED_, EQUILIBRATED_, size)) {
217
+ outcome = PIVOTED_INVERTED_;
218
+ }
219
+ else if (decisive) {
220
+ outcome = PIVOTED_SINGULAR_;
221
+ }
222
+ else {
223
+ outcome = invertPivoted_(EQUILIBRATED_, EQUILIBRATED_, size);
224
+ path = PIVOTED_PATH_;
225
+ }
226
+ }
227
+ if (outcome === PIVOTED_INVERTED_ &&
228
+ unequilibrateInverse_(EQUILIBRATED_, size, path)) {
229
+ for (let index = 0; index < count; index++) {
230
+ out[index] = EQUILIBRATED_[index];
231
+ }
232
+ return true;
233
+ }
234
+ if (outcome !== PIVOTED_SINGULAR_ && invertExact_(out, m, size)) {
235
+ return true;
236
+ }
237
+ }
238
+ for (let index = 0; index < count; index++) {
239
+ out[index] = Number.NaN;
240
+ }
241
+ return false;
242
+ }
243
+ /**
244
+ * The last chance of a matrix inversion, for a matrix that every binary64
245
+ * elimination declared singular or out of range: `m`, a square matrix of `size`
246
+ * rows (at most 4) in any layout, inverted in exact `bigint` arithmetic and
247
+ * each entry rounded once to the nearest binary64. Writes the inverse into
248
+ * `out` and returns `true`, or returns `false`, writing nothing, exactly when
249
+ * `m` is singular, an entry is not finite, or an entry of the inverse is beyond
250
+ * the range of a binary64 number. `out` may be `m`.
251
+ *
252
+ * A matrix can be invertible with an inverse that fits and still lose its
253
+ * determinant to rounding in any floating-point elimination: rows that differ
254
+ * only in an entry far below their others (`[[1, 1, 0, 0], [1, 1, 2^-600, 0],
255
+ * …]` once its rows and columns are permuted and scaled) cancel to an exact
256
+ * zero. The entries are integers times one common power of two, so the adjugate
257
+ * and the determinant are exact integers (Laplace expansion), and each entry of
258
+ * the inverse is their quotient, rounded once.
259
+ *
260
+ * Allocates (`bigint` values): it runs only after the binary64 paths fail. Time
261
+ * complexity: O(size!) `bigint` products of up to `size` × 2,100 bits.
262
+ */
263
+ export function invertExact_(out, m, size) {
264
+ let smallest = Number.POSITIVE_INFINITY;
265
+ for (let index = 0; index < size * size; index++) {
266
+ const value = m[index];
267
+ if (!Number.isFinite(value)) {
268
+ return false;
269
+ }
270
+ if (value !== 0) {
271
+ smallest = Math.min(smallest, float64ToParts(value).exponent);
272
+ }
273
+ }
274
+ if (smallest === Number.POSITIVE_INFINITY) {
275
+ return false;
276
+ }
277
+ // m = integers · 2^smallest.
278
+ const integers = [];
279
+ for (let index = 0; index < size * size; index++) {
280
+ const { significand, exponent } = float64ToParts(m[index]);
281
+ integers.push(significand << BigInt(exponent - smallest));
282
+ }
283
+ const indices = Array.from({ length: size }, (_, index) => index);
284
+ const cofactors = [];
285
+ for (let row = 0; row < size; row++) {
286
+ for (let column = 0; column < size; column++) {
287
+ const minor = determinantExact_(integers, size, indices.filter((index) => index !== row), indices.filter((index) => index !== column));
288
+ cofactors.push((row + column) % 2 === 0 ? minor : -minor);
289
+ }
290
+ }
291
+ let determinant = 0n;
292
+ for (let column = 0; column < size; column++) {
293
+ determinant += integers[column] * cofactors[column];
294
+ }
295
+ if (determinant === 0n) {
296
+ return false;
297
+ }
298
+ // inverse = adjugate / determinant · 2^-smallest, the adjugate the
299
+ // transposed cofactors.
300
+ const inverse = [];
301
+ for (let row = 0; row < size; row++) {
302
+ for (let column = 0; column < size; column++) {
303
+ const value = ratioToFloat64(cofactors[column * size + row], determinant, -smallest);
304
+ if (!Number.isFinite(value)) {
305
+ return false;
306
+ }
307
+ inverse.push(value);
308
+ }
309
+ }
310
+ for (let index = 0; index < size * size; index++) {
311
+ out[index] = inverse[index];
312
+ }
313
+ return true;
314
+ }
315
+ /** The determinant of the rows and columns of `matrix` listed, by Laplace. */
316
+ function determinantExact_(matrix, size, rows, columns) {
317
+ const row = rows[0];
318
+ if (row === undefined) {
319
+ return 1n;
320
+ }
321
+ const rest = rows.slice(1);
322
+ let determinant = 0n;
323
+ for (let position = 0; position < columns.length; position++) {
324
+ const entry = matrix[row * size + columns[position]];
325
+ if (entry !== 0n) {
326
+ const minor = determinantExact_(matrix, size, rest, columns.filter((_, index) => index !== position));
327
+ determinant += position % 2 === 0 ? entry * minor : -entry * minor;
328
+ }
329
+ }
330
+ return determinant;
331
+ }
332
+ /** The working storage of {@link invertPivoted_}, row-major, up to 4 × 4. */
333
+ const FACTORS_ = new Float64Array(16);
334
+ const INVERSE_ = new Float64Array(16);
335
+ const PERMUTATION_ = new Int32Array(4);
336
+ /**
337
+ * What {@link invertPivoted_} found: the inverse, a singularity its exact
338
+ * elimination proves, or neither, when the elimination rounded and a pivot is
339
+ * zero or the inverse leaves the range.
340
+ */
341
+ const PIVOTED_INVERTED_ = 1;
342
+ const PIVOTED_SINGULAR_ = 0;
343
+ const PIVOTED_UNSETTLED_ = -1;
344
+ /** Below it, `twoProductErrorInRange` is no longer exact. */
345
+ const EXACT_PRODUCT_MIN_ = 2 ** -969;
346
+ /**
347
+ * Inverts `m`, a column-major square matrix of `size` rows (at most 4), into
348
+ * `out` and returns {@link PIVOTED_INVERTED_}; otherwise writes nothing and
349
+ * returns {@link PIVOTED_SINGULAR_} when an entry of `m` is not finite or its
350
+ * elimination, exact throughout, meets a zero pivot, and
351
+ * {@link PIVOTED_UNSETTLED_} when the elimination rounded or an entry of the
352
+ * inverse is not finite: rounding can make a singular matrix look invertible
353
+ * and an invertible one singular, so neither is then proved. `out` may be `m`.
354
+ * Meant for the matrix {@link equilibrateForInversion_} wrote, whose every row
355
+ * and column has an entry of magnitude in `[1, 2)`, so the partial pivoting
356
+ * compares rows of one scale (Golub and Van Loan, §3.5.2), after a cofactor
357
+ * expansion of it found its determinant lost to rounding.
358
+ *
359
+ * LU factorisation with partial pivoting, `P · m = L · U` (Golub and Van Loan,
360
+ * "Matrix Computations", 4th ed., algorithm 3.4.1), then `L · U · x = P · e_j`
361
+ * solved for every column `e_j` of the identity by forward and back
362
+ * substitution (§3.1). Backward stable whatever the determinant: no product of
363
+ * more than two entries is formed, so a matrix whose cofactors cancel or whose
364
+ * determinant underflows while its inverse fits is inverted all the same. Every
365
+ * division, product and difference of the factorisation is checked for rounding
366
+ * (`twoProductErrorInRange`, `twoSumError`): when none rounds, `L · U` is
367
+ * exactly `P · m`, and its pivots decide whether `m` is singular.
368
+ *
369
+ * Time complexity: O(size³), with no allocation.
370
+ */
371
+ export function invertPivoted_(out, m, size) {
372
+ let check = 0;
373
+ for (let row = 0; row < size; row++) {
374
+ PERMUTATION_[row] = row;
375
+ for (let column = 0; column < size; column++) {
376
+ const value = m[column * size + row];
377
+ FACTORS_[row * size + column] = value;
378
+ check += value - value;
379
+ }
380
+ }
381
+ // `x - x` is 0 for a finite `x` and NaN otherwise.
382
+ if (check !== 0) {
383
+ return PIVOTED_SINGULAR_;
384
+ }
385
+ let exact = true;
386
+ for (let pivot = 0; pivot < size; pivot++) {
387
+ let pivotRow = pivot;
388
+ let largest = Math.abs(FACTORS_[pivot * size + pivot]);
389
+ for (let row = pivot + 1; row < size; row++) {
390
+ const magnitude = Math.abs(FACTORS_[row * size + pivot]);
391
+ if (magnitude > largest) {
392
+ largest = magnitude;
393
+ pivotRow = row;
394
+ }
395
+ }
396
+ if (largest === 0) {
397
+ return exact ? PIVOTED_SINGULAR_ : PIVOTED_UNSETTLED_;
398
+ }
399
+ if (pivotRow !== pivot) {
400
+ for (let column = 0; column < size; column++) {
401
+ const swap = FACTORS_[pivot * size + column];
402
+ FACTORS_[pivot * size + column] = FACTORS_[pivotRow * size + column];
403
+ FACTORS_[pivotRow * size + column] = swap;
404
+ }
405
+ const swap = PERMUTATION_[pivot];
406
+ PERMUTATION_[pivot] = PERMUTATION_[pivotRow];
407
+ PERMUTATION_[pivotRow] = swap;
408
+ }
409
+ const divisor = FACTORS_[pivot * size + pivot];
410
+ for (let row = pivot + 1; row < size; row++) {
411
+ const entry = FACTORS_[row * size + pivot];
412
+ const multiplier = entry / divisor;
413
+ FACTORS_[row * size + pivot] = multiplier;
414
+ if (multiplier === 0) {
415
+ exact &&= entry === 0;
416
+ continue;
417
+ }
418
+ if (exact) {
419
+ const back = multiplier * divisor;
420
+ exact =
421
+ back === entry &&
422
+ Math.abs(back) >= EXACT_PRODUCT_MIN_ &&
423
+ twoProductErrorInRange(multiplier, divisor, back) === 0;
424
+ }
425
+ for (let column = pivot + 1; column < size; column++) {
426
+ const factor = FACTORS_[pivot * size + column];
427
+ const minuend = FACTORS_[row * size + column];
428
+ const product = multiplier * factor;
429
+ const difference = minuend - product;
430
+ FACTORS_[row * size + column] = difference;
431
+ if (exact && factor !== 0) {
432
+ exact =
433
+ Math.abs(product) >= EXACT_PRODUCT_MIN_ &&
434
+ twoProductErrorInRange(multiplier, factor, product) === 0 &&
435
+ twoSumError(minuend, -product, difference) === 0;
436
+ }
437
+ }
438
+ }
439
+ }
440
+ // Column `j` of the inverse, stored column-major as `out` is.
441
+ check = 0;
442
+ for (let column = 0; column < size; column++) {
443
+ const base = column * size;
444
+ for (let row = 0; row < size; row++) {
445
+ let value = PERMUTATION_[row] === column ? 1 : 0;
446
+ for (let index = 0; index < row; index++) {
447
+ value -= FACTORS_[row * size + index] * INVERSE_[base + index];
448
+ }
449
+ INVERSE_[base + row] = value;
450
+ }
451
+ for (let row = size - 1; row >= 0; row--) {
452
+ let value = INVERSE_[base + row];
453
+ for (let index = row + 1; index < size; index++) {
454
+ value -= FACTORS_[row * size + index] * INVERSE_[base + index];
455
+ }
456
+ const quotient = value / FACTORS_[row * size + row];
457
+ INVERSE_[base + row] = quotient;
458
+ check += quotient - quotient;
459
+ }
460
+ }
461
+ // An exact factorisation with nonzero pivots proves `m` invertible, and its
462
+ // inverse, too large here, may still fit once scaled back: exact arithmetic
463
+ // settles it. A rounded one is a factorisation of `P · m + ΔA` with |ΔA| ≤
464
+ // γₙ · |L| · |U| (Higham, "Accuracy and Stability of Numerical Algorithms",
465
+ // theorem 9.3); while ‖m⁻¹ ΔA‖ stays far below 1, which the computed inverse
466
+ // bounds, `m` is invertible and the inverse backward stable. Past that,
467
+ // exact arithmetic settles it too.
468
+ if (check !== 0 || (!exact && !isFactorisationCertain_(size))) {
469
+ return PIVOTED_UNSETTLED_;
470
+ }
471
+ for (let index = 0; index < size * size; index++) {
472
+ out[index] = INVERSE_[index];
473
+ }
474
+ return PIVOTED_INVERTED_;
475
+ }
476
+ /**
477
+ * Whether `‖X‖∞ · γₙ · ‖|L| · |U|‖∞` is at most {@link PIVOTED_MARGIN_}, for
478
+ * the factors in {@link FACTORS_} and the inverse `X` in {@link INVERSE_}.
479
+ */
480
+ function isFactorisationCertain_(size) {
481
+ let inverseNorm = 0;
482
+ let productNorm = 0;
483
+ for (let row = 0; row < size; row++) {
484
+ let inverseRow = 0;
485
+ for (let column = 0; column < size; column++) {
486
+ inverseRow += Math.abs(INVERSE_[column * size + row]);
487
+ }
488
+ inverseNorm = Math.max(inverseNorm, inverseRow);
489
+ // Row `row` of |L| · |U|: L is unit lower triangular.
490
+ let productRow = 0;
491
+ for (let index = 0; index <= row; index++) {
492
+ let upperRow = 0;
493
+ for (let column = index; column < size; column++) {
494
+ upperRow += Math.abs(FACTORS_[index * size + column]);
495
+ }
496
+ productRow +=
497
+ (index === row ? 1 : Math.abs(FACTORS_[row * size + index])) *
498
+ upperRow;
499
+ }
500
+ productNorm = Math.max(productNorm, productRow);
501
+ }
502
+ // γₙ = n·u / (1 − n·u), rounded up generously.
503
+ return (inverseNorm * (size + 1) * UNIT_ROUNDOFF_ * productNorm <= PIVOTED_MARGIN_);
504
+ }
505
+ /** Half a unit in the last place of 1. */
506
+ export const UNIT_ROUNDOFF_ = 2 ** -53;
507
+ /**
508
+ * The relative error a cofactor expansion's determinant, and its cofactors
509
+ * against the largest of them, may carry for its inverse to be accepted: a
510
+ * normwise backward error of at most about `2^-40`.
511
+ *
512
+ * An error bound `r · u + k · η` (rounding, then `k` products that may fall in
513
+ * the subnormal range, each adding at most `η = 2^-1073`) is accepted against a
514
+ * value `v` when `r · u ≤ ROUNDING_TOLERANCE_ · v` and `k · UNDERFLOW_UNIT_ ≤
515
+ * UNDERFLOW_TOLERANCE_ · v`: the first share is `(1 − 2^-20)` of
516
+ * `INVERSE_TOLERANCE_`, the second `2^-20` of it, both scaled by `2^1000` so
517
+ * that no operand is subnormal. Arithmetic on a subnormal number takes a
518
+ * microcode assist of about a hundred cycles on x86, which on every call would
519
+ * cost the plain path several times its own time.
520
+ */
521
+ export const INVERSE_TOLERANCE_ = 2 ** -41;
522
+ /** `INVERSE_TOLERANCE_ · (1 − 2^-20)`, the share of the rounding errors. */
523
+ export const ROUNDING_TOLERANCE_ = INVERSE_TOLERANCE_ * (1 - 2 ** -20);
524
+ /** `η · 2^1000`, the error of a product in the subnormal range, rounded up. */
525
+ export const UNDERFLOW_UNIT_ = 2 ** -73;
526
+ /** `INVERSE_TOLERANCE_ · 2^-20 · 2^1000`, the share of the underflows. */
527
+ export const UNDERFLOW_TOLERANCE_ = 2 ** 939;
528
+ /**
529
+ * The magnitude of the determinant {@link isWithinTolerance3_} judges: through
530
+ * typed storage, as a double passed to a call the engine does not inline is
531
+ * boxed.
532
+ */
533
+ export const BOUND_INPUT_ = new Float64Array(1);
534
+ /**
535
+ * Whether the forward error bound of a 3 × 3 cofactor expansion of the
536
+ * column-major `m` (its first nine entries) keeps the determinant, of the
537
+ * magnitude in {@link BOUND_INPUT_}, within `2^-41` of itself and every minor
538
+ * within `2^-41 / 3` of the largest of them (Higham, "Accuracy and Stability of
539
+ * Numerical Algorithms", §3.1): a minor `x·y − z·w` is within `3u·(|x·y| +
540
+ * |z·w|) + η` of its value, the determinant, along a row or a column, within
541
+ * `7u·P + (M₁ + 2)·2η`, `P` the permanent of `|m|` and `M₁` the sum of that row
542
+ * or column, at most the sum of all of `|m|`. The tight bound behind the cheap
543
+ * one of `mat3x3Invert` and `affine3Invert`, whose minors are the same products
544
+ * in either order, so of the same magnitudes.
545
+ *
546
+ * Time complexity: O(1), with no allocation.
547
+ */
548
+ export function isWithinTolerance3_(m) {
549
+ const m0 = m[0];
550
+ const m1 = m[1];
551
+ const m2 = m[2];
552
+ const m3 = m[3];
553
+ const m4 = m[4];
554
+ const m5 = m[5];
555
+ const m6 = m[6];
556
+ const m7 = m[7];
557
+ const m8 = m[8];
558
+ const a0 = Math.abs(m0);
559
+ const a1 = Math.abs(m1);
560
+ const a2 = Math.abs(m2);
561
+ const a3 = Math.abs(m3);
562
+ const a4 = Math.abs(m4);
563
+ const a5 = Math.abs(m5);
564
+ const a6 = Math.abs(m6);
565
+ const a7 = Math.abs(m7);
566
+ const a8 = Math.abs(m8);
567
+ const p0 = a4 * a8 + a7 * a5;
568
+ const p1 = a7 * a2 + a1 * a8;
569
+ const p2 = a1 * a5 + a4 * a2;
570
+ const permanent = a0 * p0 + a3 * p1 + a6 * p2;
571
+ const largestBound = Math.max(p0, p1, p2, a6 * a5 + a3 * a8, a0 * a8 + a6 * a2, a3 * a2 + a0 * a5, a3 * a7 + a6 * a4, a6 * a1 + a0 * a7, a0 * a4 + a3 * a1);
572
+ const largestCofactor = Math.max(Math.abs(m4 * m8 - m7 * m5), Math.abs(m7 * m2 - m1 * m8), Math.abs(m1 * m5 - m4 * m2), Math.abs(m6 * m5 - m3 * m8), Math.abs(m0 * m8 - m6 * m2), Math.abs(m3 * m2 - m0 * m5), Math.abs(m3 * m7 - m6 * m4), Math.abs(m6 * m1 - m0 * m7), Math.abs(m0 * m4 - m3 * m1));
573
+ const magnitude = BOUND_INPUT_[0];
574
+ const entries = a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8;
575
+ return (7 * UNIT_ROUNDOFF_ * permanent <= ROUNDING_TOLERANCE_ * magnitude &&
576
+ (entries + 2) * 2 * UNDERFLOW_UNIT_ <= UNDERFLOW_TOLERANCE_ * magnitude &&
577
+ 9 * UNIT_ROUNDOFF_ * largestBound <=
578
+ ROUNDING_TOLERANCE_ * largestCofactor &&
579
+ 3 * UNDERFLOW_UNIT_ <= UNDERFLOW_TOLERANCE_ * largestCofactor);
580
+ }
581
+ /** How far below 1 `‖m⁻¹ ΔA‖` must stay for a rounded factorisation. */
582
+ const PIVOTED_MARGIN_ = 2 ** -10;
583
+ /**
584
+ * The values {@link isCofactorExpansionExact_} recomputes: the 2 × 2 minors,
585
+ * then the cofactors of a 4 × 4 matrix.
586
+ */
587
+ const EXPANSION_ = new Float64Array(34);
588
+ /** Whether `a · b` rounded to `product` is exact. */
589
+ function isProductExact_(a, b, product) {
590
+ return product === 0
591
+ ? a === 0 || b === 0
592
+ : Math.abs(product) >= EXACT_PRODUCT_MIN_ &&
593
+ twoProductErrorInRange(a, b, product) === 0;
594
+ }
595
+ /**
596
+ * `m[a] · m[b] − m[c] · m[d]` into `EXPANSION_[slot]`, as the cofactor
597
+ * expansions compute it; returns whether no step rounded.
598
+ */
599
+ function isMinorExact_(m, a, b, c, d, slot) {
600
+ const left = m[a] * m[b];
601
+ const right = m[c] * m[d];
602
+ const difference = left - right;
603
+ EXPANSION_[slot] = difference;
604
+ return (isProductExact_(m[a], m[b], left) &&
605
+ isProductExact_(m[c], m[d], right) &&
606
+ twoSumError(left, -right, difference) === 0);
607
+ }
608
+ /**
609
+ * `±((m[i] · E[x] − m[j] · E[y]) + m[k] · E[z])` of {@link EXPANSION_} into
610
+ * `EXPANSION_[slot]`, as the 4 × 4 cofactor expansion computes a cofactor;
611
+ * returns whether no step rounded.
612
+ */
613
+ function isCofactorExact_(m, i, x, j, y, k, z, slot, negate) {
614
+ const first = m[i] * EXPANSION_[x];
615
+ const second = m[j] * EXPANSION_[y];
616
+ const third = m[k] * EXPANSION_[z];
617
+ const difference = first - second;
618
+ const sum = difference + third;
619
+ EXPANSION_[slot] = negate ? -sum : sum;
620
+ return (isProductExact_(m[i], EXPANSION_[x], first) &&
621
+ isProductExact_(m[j], EXPANSION_[y], second) &&
622
+ isProductExact_(m[k], EXPANSION_[z], third) &&
623
+ twoSumError(first, -second, difference) === 0 &&
624
+ twoSumError(difference, third, sum) === 0);
625
+ }
626
+ /**
627
+ * `((m[i] · E[x] + m[j] · E[y]) + m[k] · E[z]) + m[l] · E[w]` of
628
+ * {@link EXPANSION_}, the last term only when `l` is not negative, as the
629
+ * cofactor expansions compute the determinant; returns whether no step
630
+ * rounded.
631
+ */
632
+ function isDeterminantExact_(m, i, x, j, y, k, z, l, w) {
633
+ const first = m[i] * EXPANSION_[x];
634
+ const second = m[j] * EXPANSION_[y];
635
+ const third = m[k] * EXPANSION_[z];
636
+ const partial = first + second;
637
+ const sum = partial + third;
638
+ let exact = isProductExact_(m[i], EXPANSION_[x], first) &&
639
+ isProductExact_(m[j], EXPANSION_[y], second) &&
640
+ isProductExact_(m[k], EXPANSION_[z], third) &&
641
+ twoSumError(first, second, partial) === 0 &&
642
+ twoSumError(partial, third, sum) === 0;
643
+ if (l >= 0) {
644
+ const fourth = m[l] * EXPANSION_[w];
645
+ exact &&=
646
+ isProductExact_(m[l], EXPANSION_[w], fourth) &&
647
+ twoSumError(sum, fourth, sum + fourth) === 0;
648
+ }
649
+ return exact;
650
+ }
651
+ /**
652
+ * Whether the cofactor expansion of `mat3x3Invert` (`size` 3) or `mat4x4Invert`
653
+ * (`size` 4) of the column-major `m` rounds nowhere: every product and sum of
654
+ * its minors, cofactors and determinant recomputed in the same order and
655
+ * checked (`twoProductErrorInRange`, `twoSumError`). Then the cofactors and the
656
+ * determinant are exact, and the inverse is each cofactor over the determinant,
657
+ * rounded at most twice, however they cancel (an integer matrix of determinant
658
+ * 1). The second chance of a cofactor expansion whose error bound refused it.
659
+ *
660
+ * Time complexity: O(1), with no allocation.
661
+ */
662
+ export function isCofactorExpansionExact_(m, size) {
663
+ if (size === 3) {
664
+ return (isMinorExact_(m, 4, 8, 7, 5, 0) &&
665
+ isMinorExact_(m, 7, 2, 1, 8, 1) &&
666
+ isMinorExact_(m, 1, 5, 4, 2, 2) &&
667
+ isMinorExact_(m, 6, 5, 3, 8, 3) &&
668
+ isMinorExact_(m, 0, 8, 6, 2, 4) &&
669
+ isMinorExact_(m, 3, 2, 0, 5, 5) &&
670
+ isMinorExact_(m, 3, 7, 6, 4, 6) &&
671
+ isMinorExact_(m, 6, 1, 0, 7, 7) &&
672
+ isMinorExact_(m, 0, 4, 3, 1, 8) &&
673
+ isDeterminantExact_(m, 0, 0, 3, 1, 6, 2, -1, 0));
674
+ }
675
+ return (isMinorExact_(m, 10, 15, 14, 11, 0) &&
676
+ isMinorExact_(m, 6, 15, 14, 7, 1) &&
677
+ isMinorExact_(m, 6, 11, 10, 7, 2) &&
678
+ isMinorExact_(m, 2, 15, 14, 3, 3) &&
679
+ isMinorExact_(m, 2, 11, 10, 3, 4) &&
680
+ isMinorExact_(m, 2, 7, 6, 3, 5) &&
681
+ isMinorExact_(m, 9, 15, 13, 11, 6) &&
682
+ isMinorExact_(m, 5, 15, 13, 7, 7) &&
683
+ isMinorExact_(m, 5, 11, 9, 7, 8) &&
684
+ isMinorExact_(m, 1, 15, 13, 3, 9) &&
685
+ isMinorExact_(m, 1, 11, 9, 3, 10) &&
686
+ isMinorExact_(m, 1, 7, 5, 3, 11) &&
687
+ isMinorExact_(m, 9, 14, 13, 10, 12) &&
688
+ isMinorExact_(m, 5, 14, 13, 6, 13) &&
689
+ isMinorExact_(m, 5, 10, 9, 6, 14) &&
690
+ isMinorExact_(m, 1, 14, 13, 2, 15) &&
691
+ isMinorExact_(m, 1, 10, 9, 2, 16) &&
692
+ isMinorExact_(m, 1, 6, 5, 2, 17) &&
693
+ isCofactorExact_(m, 5, 0, 9, 1, 13, 2, 18, false) &&
694
+ isCofactorExact_(m, 1, 0, 9, 3, 13, 4, 19, true) &&
695
+ isCofactorExact_(m, 1, 1, 5, 3, 13, 5, 20, false) &&
696
+ isCofactorExact_(m, 1, 2, 5, 4, 9, 5, 21, true) &&
697
+ isCofactorExact_(m, 4, 0, 8, 1, 12, 2, 22, true) &&
698
+ isCofactorExact_(m, 0, 0, 8, 3, 12, 4, 23, false) &&
699
+ isCofactorExact_(m, 0, 1, 4, 3, 12, 5, 24, true) &&
700
+ isCofactorExact_(m, 0, 2, 4, 4, 8, 5, 25, false) &&
701
+ isCofactorExact_(m, 4, 6, 8, 7, 12, 8, 26, false) &&
702
+ isCofactorExact_(m, 0, 6, 8, 9, 12, 10, 27, true) &&
703
+ isCofactorExact_(m, 0, 7, 4, 9, 12, 11, 28, false) &&
704
+ isCofactorExact_(m, 0, 8, 4, 10, 8, 11, 29, true) &&
705
+ isCofactorExact_(m, 4, 12, 8, 13, 12, 14, 30, true) &&
706
+ isCofactorExact_(m, 0, 12, 8, 15, 12, 16, 31, false) &&
707
+ isCofactorExact_(m, 0, 13, 4, 15, 12, 17, 32, true) &&
708
+ isCofactorExact_(m, 0, 14, 4, 16, 8, 17, 33, false) &&
709
+ isDeterminantExact_(m, 0, 18, 4, 19, 8, 20, 12, 21));
710
+ }
711
+ /**
712
+ * Where {@link writeInverseTranslation_} reads a row of the inverse and the
713
+ * translation, by size, for `dotExactInto`, which takes arrays of one length.
714
+ */
715
+ const ROWS_ = [new Float64Array(2), new Float64Array(3)];
716
+ const TRANSLATIONS_ = [new Float64Array(2), new Float64Array(3)];
717
+ /** Where `dotExactInto` writes the product of a row. */
718
+ const ROW_RESULT_ = new Float64Array(1);
719
+ /**
720
+ * The translation {@link writeInverseTranslation_} computed, before
721
+ * {@link isTranslationCertain_} vouches for it, and the bound of each row of
722
+ * the residual `B · A − I` that it uses.
723
+ */
724
+ const CANDIDATE_ = new Float64Array(3);
725
+ const RESIDUAL_ROWS_ = new Float64Array(3);
726
+ /**
727
+ * The largest `‖B · A − I‖∞` {@link isTranslationCertain_} accepts: below it,
728
+ * `1 / (1 − ‖B · A − I‖∞)` is at most `4/3`.
729
+ */
730
+ const RESIDUAL_MARGIN_ = 0.25;
731
+ /**
732
+ * Added to the bound of each row of the residual for the products that fall in
733
+ * the subnormal range, at most `2^-1075` each: a normal number, so that the
734
+ * bound never computes on subnormal ones, far above their sum.
735
+ */
736
+ const RESIDUAL_FLOOR_ = 2 ** -1000;
737
+ /**
738
+ * The homogeneous matrix of an affine transform, then its exact inverse, for
739
+ * {@link settleInverseTranslation_}: a `number[]` of doubles, like the matrices
740
+ * {@link invertExact_} otherwise sees.
741
+ */
742
+ const HOMOGENEOUS_ = Array.from({ length: 16 }, () => 0.5);
743
+ /**
744
+ * Writes the translation of the inverse of an affine transform `a` (its `size ×
745
+ * size` linear part `A`, `size` 2 or 3, column-major from `a[0]`, then its
746
+ * translation `t` from `a[offset]`, `offset` being `size²`), given the inverse
747
+ * `B` of `A`, to `out[offset]` and on, and returns `true`; or returns `false`,
748
+ * writing nothing there, exactly when an entry of the exact `−A⁻¹ · t` rounds
749
+ * past `Number.MAX_VALUE`.
750
+ *
751
+ * Each entry is the correctly rounded value of `−B · t` for the `B` given
752
+ * (`dotExactInto`), however its terms cancel, overflow or underflow. Whether it
753
+ * overflows is never read off that rounded value: a rigorous bound first proves
754
+ * the exact `−A⁻¹ · t` far enough from the threshold
755
+ * ({@link isTranslationCertain_}). When it cannot (a component within the bound
756
+ * of the threshold or past it, or a `B` too far from `A⁻¹`, as for an
757
+ * ill-conditioned `A`), `isHomogeneousInvertible(a)` decides: whether the
758
+ * inverse of the homogeneous matrix of `a`, whose linear block is `A⁻¹` and
759
+ * last column `−A⁻¹ · t`, rounds to finite numbers (`mat3x3Invert` or
760
+ * `mat4x4Invert`, exact about it). A component of `−B · t` that overflowed
761
+ * where the exact one does not is settled from `a` itself in exact arithmetic
762
+ * ({@link settleInverseTranslation_}): every component is then `−A⁻¹ · t`
763
+ * rounded once. So with a scale of `161/256` and a translation of `161 ·
764
+ * 2^1016`, where `−B · t` rounds to `−Number.MAX_VALUE`, the exact `−2^1024` is
765
+ * refused. `a` is read before anything is written, so `out` may be `a`; `B` is
766
+ * the already unscaled inverse, so no entry of it passes through the range of
767
+ * the scaled matrix.
768
+ *
769
+ * Time complexity: O(size³), with no allocation unless the exact settlement, or
770
+ * that of the homogeneous inversion, runs: for a translation near the overflow
771
+ * threshold.
772
+ */
773
+ export function writeInverseTranslation_(out, offset, inverse, size, a, isHomogeneousInvertible) {
774
+ const row = ROWS_[size - 2];
775
+ const components = TRANSLATIONS_[size - 2];
776
+ for (let index = 0; index < size; index++) {
777
+ components[index] = a[offset + index];
778
+ }
779
+ let isFinite = true;
780
+ for (let index = 0; index < size; index++) {
781
+ for (let column = 0; column < size; column++) {
782
+ row[column] = inverse[column * size + index];
783
+ }
784
+ dotExactInto(ROW_RESULT_, 0, row, components);
785
+ const value = -ROW_RESULT_[0];
786
+ CANDIDATE_[index] = value;
787
+ isFinite &&= value - value === 0;
788
+ }
789
+ if (!isTranslationCertain_(inverse, size, a) && !isHomogeneousInvertible(a)) {
790
+ return false;
791
+ }
792
+ if (!isFinite) {
793
+ return settleInverseTranslation_(out, offset, size, a);
794
+ }
795
+ for (let index = 0; index < size; index++) {
796
+ out[offset + index] = CANDIDATE_[index];
797
+ }
798
+ return true;
799
+ }
800
+ /**
801
+ * Whether every entry of the exact `x = −A⁻¹ · t` rounds to a finite number,
802
+ * proved from the candidate `y = −B · t` in {@link CANDIDATE_} (each entry
803
+ * correctly rounded) and the residual `R = B · A − I`, for the column-major `B`
804
+ * in `inverse` and the affine transform `a` of
805
+ * {@link writeInverseTranslation_}. `false` proves nothing.
806
+ *
807
+ * `x − y = (B − A⁻¹) · t = R · A⁻¹ · t = −R · x`, so `x = y − R · x`, `‖x‖∞ ≤
808
+ * ‖y‖∞ / (1 − ‖R‖∞)` and `|x_i − y_i| ≤ ‖R_i‖₁ · ‖y‖∞ / (1 − ‖R‖∞)`, `R_i` the
809
+ * row `i` of `R`. Each entry of `R`, a sum of `size + 1` terms, is computed in
810
+ * plain arithmetic within `γ_{size+1}` of the sum of their magnitudes, plus an
811
+ * underflow per product (Higham, "Accuracy and Stability of Numerical
812
+ * Algorithms", §3.1): bounded by `(size + 2) · u` of it and
813
+ * {@link RESIDUAL_FLOOR_}. With `‖R‖∞` at most {@link RESIDUAL_MARGIN_}, an
814
+ * entry `y_i` with `|y_i| + 1.5 · ‖R_i‖₁ · ‖y‖∞` within {@link INVERSE_LIMIT_}
815
+ * has an exact `x_i` below `Number.MAX_VALUE`: the `1.5` covers `4/3` and the
816
+ * roundings of the bound, the `2^-30` margin of the limit the rounding of
817
+ * `y_i`. A product of the residual that overflows, an entry of `y` that does,
818
+ * or a bound past either margin, answers `false`.
819
+ *
820
+ * Time complexity: O(size³), with no allocation.
821
+ */
822
+ function isTranslationCertain_(inverse, size, a) {
823
+ let largest = 0;
824
+ for (let index = 0; index < size; index++) {
825
+ largest = Math.max(largest, Math.abs(CANDIDATE_[index]));
826
+ }
827
+ if (!(largest <= Number.MAX_VALUE)) {
828
+ return false;
829
+ }
830
+ for (let row = 0; row < size; row++) {
831
+ let reach = RESIDUAL_FLOOR_;
832
+ for (let column = 0; column < size; column++) {
833
+ let sum = row === column ? -1 : 0;
834
+ let magnitude = row === column ? 1 : 0;
835
+ for (let index = 0; index < size; index++) {
836
+ const product = inverse[index * size + row] * a[column * size + index];
837
+ sum += product;
838
+ magnitude += Math.abs(product);
839
+ }
840
+ reach += Math.abs(sum) + (size + 2) * UNIT_ROUNDOFF_ * magnitude;
841
+ }
842
+ // NaN, from a product that overflowed, fails it too.
843
+ if (!(reach <= RESIDUAL_MARGIN_)) {
844
+ return false;
845
+ }
846
+ RESIDUAL_ROWS_[row] = reach;
847
+ }
848
+ for (let row = 0; row < size; row++) {
849
+ if (!(Math.abs(CANDIDATE_[row]) + 1.5 * RESIDUAL_ROWS_[row] * largest <=
850
+ INVERSE_LIMIT_)) {
851
+ return false;
852
+ }
853
+ }
854
+ return true;
855
+ }
856
+ /**
857
+ * The translation of the inverse of the affine transform `a` of
858
+ * {@link writeInverseTranslation_}, settled from its own coefficients: the last
859
+ * column of the exact inverse of its homogeneous matrix ({@link invertExact_}),
860
+ * whose linear block is `A⁻¹` and last column `−A⁻¹ · t`, each entry rounded
861
+ * once. Writes it to `out[offset]` and on and returns `true`, or returns
862
+ * `false`, writing nothing, when an entry overflows (`A⁻¹` itself, which the
863
+ * caller has inverted, fits). `a` is read before anything is written.
864
+ *
865
+ * Allocates (`bigint` values). Time complexity: that of {@link invertExact_}
866
+ * for `size + 1` rows.
867
+ */
868
+ function settleInverseTranslation_(out, offset, size, a) {
869
+ const order = size + 1;
870
+ for (let column = 0; column < order; column++) {
871
+ for (let row = 0; row < order; row++) {
872
+ HOMOGENEOUS_[column * order + row] =
873
+ row < size ? a[column * size + row] : column === size ? 1 : 0;
874
+ }
875
+ }
876
+ if (!invertExact_(HOMOGENEOUS_, HOMOGENEOUS_, order)) {
877
+ return false;
878
+ }
879
+ for (let index = 0; index < size; index++) {
880
+ out[offset + index] = HOMOGENEOUS_[size * order + index];
881
+ }
882
+ return true;
883
+ }
884
+ //# sourceMappingURL=_invert.js.map