@ac-kit/math-linear 0.3.0 → 0.5.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.
- package/CHANGELOG.md +147 -0
- package/README.md +63 -7
- package/dist/_euclidean-norm.d.ts +18 -0
- package/dist/_euclidean-norm.d.ts.map +1 -0
- package/dist/_euclidean-norm.js +73 -0
- package/dist/_euclidean-norm.js.map +1 -0
- package/dist/_invert.d.ts +209 -14
- package/dist/_invert.d.ts.map +1 -1
- package/dist/_invert.js +869 -33
- package/dist/_invert.js.map +1 -1
- package/dist/_matrix-shape.d.ts +4 -0
- package/dist/_matrix-shape.d.ts.map +1 -0
- package/dist/_matrix-shape.js +7 -0
- package/dist/_matrix-shape.js.map +1 -0
- package/dist/_slerp.d.ts +14 -0
- package/dist/_slerp.d.ts.map +1 -1
- package/dist/_slerp.js +56 -0
- package/dist/_slerp.js.map +1 -1
- package/dist/affine2.d.ts +17 -5
- package/dist/affine2.d.ts.map +1 -1
- package/dist/affine2.js +96 -34
- package/dist/affine2.js.map +1 -1
- package/dist/affine3.d.ts +17 -4
- package/dist/affine3.d.ts.map +1 -1
- package/dist/affine3.js +134 -60
- package/dist/affine3.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/lu-decomposition.d.ts +142 -0
- package/dist/lu-decomposition.d.ts.map +1 -0
- package/dist/lu-decomposition.js +416 -0
- package/dist/lu-decomposition.js.map +1 -0
- package/dist/mat2x2.d.ts +16 -4
- package/dist/mat2x2.d.ts.map +1 -1
- package/dist/mat2x2.js +76 -33
- package/dist/mat2x2.js.map +1 -1
- package/dist/mat3x3.d.ts +27 -5
- package/dist/mat3x3.d.ts.map +1 -1
- package/dist/mat3x3.js +71 -34
- package/dist/mat3x3.js.map +1 -1
- package/dist/mat4x4.d.ts +34 -8
- package/dist/mat4x4.d.ts.map +1 -1
- package/dist/mat4x4.js +180 -56
- package/dist/mat4x4.js.map +1 -1
- package/dist/matrix.d.ts +136 -0
- package/dist/matrix.d.ts.map +1 -0
- package/dist/matrix.js +308 -0
- package/dist/matrix.js.map +1 -0
- package/dist/projection.d.ts +16 -1
- package/dist/projection.d.ts.map +1 -1
- package/dist/projection.js +49 -0
- package/dist/projection.js.map +1 -1
- package/dist/qr-decomposition.d.ts +283 -0
- package/dist/qr-decomposition.d.ts.map +1 -0
- package/dist/qr-decomposition.js +1071 -0
- package/dist/qr-decomposition.js.map +1 -0
- package/dist/quaternion.d.ts +6 -4
- package/dist/quaternion.d.ts.map +1 -1
- package/dist/quaternion.js +8 -50
- package/dist/quaternion.js.map +1 -1
- package/dist/singular-value-decomposition.d.ts +154 -0
- package/dist/singular-value-decomposition.d.ts.map +1 -0
- package/dist/singular-value-decomposition.js +474 -0
- package/dist/singular-value-decomposition.js.map +1 -0
- package/dist/symmetric-eigen-decomposition.d.ts +92 -0
- package/dist/symmetric-eigen-decomposition.d.ts.map +1 -0
- package/dist/symmetric-eigen-decomposition.js +289 -0
- package/dist/symmetric-eigen-decomposition.js.map +1 -0
- package/dist/vec2-array-componentwise.d.ts +18 -0
- package/dist/vec2-array-componentwise.d.ts.map +1 -1
- package/dist/vec2-array-componentwise.js +48 -0
- package/dist/vec2-array-componentwise.js.map +1 -1
- package/dist/vec2-array.d.ts +16 -0
- package/dist/vec2-array.d.ts.map +1 -1
- package/dist/vec2-array.js +42 -0
- package/dist/vec2-array.js.map +1 -1
- package/dist/vec3-array-componentwise.d.ts +18 -0
- package/dist/vec3-array-componentwise.d.ts.map +1 -1
- package/dist/vec3-array-componentwise.js +52 -0
- package/dist/vec3-array-componentwise.js.map +1 -1
- package/dist/vec3.d.ts +5 -5
- package/dist/vec3.d.ts.map +1 -1
- package/dist/vec3.js +39 -13
- package/dist/vec3.js.map +1 -1
- package/dist/vec4-array-componentwise.d.ts +43 -0
- package/dist/vec4-array-componentwise.d.ts.map +1 -1
- package/dist/vec4-array-componentwise.js +120 -0
- package/dist/vec4-array-componentwise.js.map +1 -1
- package/dist/vec4.d.ts +4 -2
- package/dist/vec4.d.ts.map +1 -1
- package/dist/vec4.js +6 -29
- package/dist/vec4.js.map +1 -1
- package/package.json +11 -9
package/dist/_invert.js
CHANGED
|
@@ -1,47 +1,883 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
*
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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
|
+
}
|
|
18
60
|
}
|
|
19
|
-
if (
|
|
20
|
-
|
|
61
|
+
if (exponent === NO_EXPONENT_) {
|
|
62
|
+
return false;
|
|
21
63
|
}
|
|
64
|
+
EXPONENTS_[row] = exponent;
|
|
22
65
|
}
|
|
23
|
-
|
|
24
|
-
|
|
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]));
|
|
25
122
|
}
|
|
26
|
-
const
|
|
27
|
-
for (let
|
|
28
|
-
|
|
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
|
+
}
|
|
29
138
|
}
|
|
30
|
-
return
|
|
139
|
+
return true;
|
|
31
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);
|
|
32
174
|
/**
|
|
33
|
-
*
|
|
34
|
-
* `
|
|
35
|
-
*
|
|
36
|
-
*
|
|
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.
|
|
37
206
|
*/
|
|
38
|
-
export function
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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];
|
|
42
267
|
if (!Number.isFinite(value)) {
|
|
43
268
|
return false;
|
|
44
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];
|
|
45
881
|
}
|
|
46
882
|
return true;
|
|
47
883
|
}
|