mutable design
Design goal
mutable is the execution-oriented half of the repository. It stores a
matrix in one flat row-major array, lets callers update it in place and work
through live views, and implements the floating-point numerical routines:
determinant, inverse, rank, row reduction, Cholesky factorization, symmetric
eigenvalues and the power method. The public API still reads like value
operations wherever possible; mutation is confined to methods that return
Unit and to the views, so callers can tell from a signature whether a call
changes its receiver.
Constraints
- The package must run on all four MoonBit targets (
native,js,wasm,wasm-gc) with one public specification. - It may depend only on
error,internaland the upstream scalar packages, not on the experimentalalgebraandcontainerlayers. - Element types are generic. The numerical routines can only assume the
luna-genericstructure traits (Field,Num) plusCompare,Sqrtand this package’sTolerance; they cannot inspect the floating-point format. - Its names, argument order and checked/unchecked conventions follow
immutwherever both packages offer an operation.
Design decisions
Flat row-major storage
Options. An array of row arrays, a persistent structure, or one flat
array. Decision. One Array[T] with entry at , shared by
all four targets. Why. It gives access with one bounds check per
coordinate, contiguous rows for the inner loops of elimination and products,
and zero-cost row and column views. from_array adopts the caller’s array so
that large inputs need not be copied; the price is aliasing, which the API
documents.
Views instead of copies
row_view, col_view and to_transpose return live views in . A
view is a pair (matrix, index) or a wrapper, so writes go to the shared storage
and no synchronization is needed. Materializing is always explicit
(to_vector, materialize, transpose).
Target-specific kernels with shared semantics
The package has one source file per target for the matrix, LU, view and transpose code. They differ only in loop structure (unrolling, packing, avoidance of division in index computations) chosen for each backend; the public semantics, including bounds and error behaviour, are identical, and the tests run on all four targets. Floating-point results may differ in the last bits because summation orders differ.
Tolerance-based decisions
Elimination must decide when a computed quantity “is zero”. The package uses
one absolute threshold = Tolerance::tolerance() = for
Double and Float, applied as follows:
| Routine | Test |
|---|---|
LU (determinant for , inverse, is_invertible) | pivot means singular |
inverse of a diagonal matrix | means singular |
rank | largest remaining means no pivot; a multiplier is dropped |
reduce_row_elimination | pivot candidate is set to zero and skipped; column entries are set to zero |
cholesky_decomposition | radicand means not positive definite |
is_symmetric (also the precondition of eigen) | counts as equal |
power_method | residual accepts; or gives None |
The structural fast paths and the internal decisions of eigen do not use
: the fast paths require the structure exactly, and eigen deflates
relative to the entries (see below). An absolute threshold is simple and predictable, but it is not scale
invariant. Scaling by makes every pivot fall below , so a
perfectly conditioned matrix is reported singular; scaling by lets a
numerically singular matrix pass. Scale data to order one before calling
these routines. For Float, is far below the unit roundoff
, so for data of order one the tests effectively
check for exact zeros, and nearly singular Float matrices are not detected.
The trait is closed (pub, not pub(open)), so these two instances are the
only ones; a scale-aware tolerance policy is future work and would be a
breaking change.
Fast paths
inverse recognizes the identity (returns a copy), diagonal matrices
(inverts the diagonal) and permutation matrices (returns the transpose, since
for a matrix whose columns are distinct coordinate
vectors). cholesky_decomposition recognizes the identity and diagonal
matrices, and determinant recognizes triangular matrices for and
multiplies the diagonal. Each test costs and saves an
factorization. The tests are exact (entries compared with and ), so a
shortcut is taken only when it returns what the general algorithm would; a
matrix that is merely close to the structure goes through the general path.
Checked forms without changing the kernels
Every checked method validates (squareness, exponent sign, non-emptiness,
lengths) and then calls its unchecked partner, which keeps the original
aborting or Option behaviour. Matrix multiplication also provides
matmul, which returns a DimensionMismatch error before entering the same
unchecked kernel. The * operator keeps its aborting behavior, and
unchecked_matmul remains available when callers establish compatible shapes.
Symmetric eigenvalues only
General real matrices can have complex eigenvalues, which a function
returning Vector[T] cannot represent for real T. eigen therefore accepts
only symmetric matrices, for which all eigenvalues are real and an orthonormal
eigenbasis exists, and aborts otherwise.
Which traits the routines require, and why
| Bound | Needed for |
|---|---|
AddMonoid + Mul | products, mul_vec, dot, trace: sums of products starting from 0 |
Semiring | pow: needs 1 for and distributivity for associativity of the product |
Field | elimination divides by pivots; mean divides by |
Num | abs for pivot selection and every tolerance test |
Compare | comparing magnitudes |
Sqrt | Cholesky diagonal, Householder norms, Givens rotations, , std_dev |
Tolerance | the zero decisions above |
Field is commutative in luna-generic, which the derivations below use (for
example and ).
Mathematical background
Throughout, is the unit roundoff ( for Double, for
Float), with
, and
The second fact11 Higham, Lemma 3.1. The proof is an induction on using . is what turns “each operation is rounded” into bounds for whole algorithms. Inequalities between matrices hold entry-wise, and is the matrix of absolute values. A flop is one floating-point addition, subtraction, multiplication or division.
Matrix product
costs multiply-adds, flops. The kernels sum in different orders (four partial products per step in the unrolled kernels; a packed copy of the columns of for products of at least ), but in any order each product passes through one multiplication and at most additions, so it carries a factor and
Results on different targets therefore agree to that accuracy, not bit for bit.
LU factorization with partial pivoting
For square , Gaussian elimination with partial pivoting computes a permutation , a unit lower triangular and an upper triangular with
Derivation. Write . At step the algorithm chooses the row with the largest and swaps it into position (a transposition ). It then subtracts multiples of row from the rows below, which is multiplication by the Gauss transform
so that and column below the diagonal becomes zero. After steps
Since , , and a later transposition () only exchanges entries of : with . Moving all permutations to the right gives with , hence with
This is why the code can store the multipliers in place of the eliminated entries and swap whole rows, multipliers included: the stored lower triangle is exactly . The pivot choice gives .
Cost. Step updates an block with one multiply and one subtract per entry, so
flops.
Determinant. Taking determinants of with and for exchanges,
Solving and the inverse. becomes (forward substitution, ) and (back substitution, ). Each costs flops per right-hand side. The inverse is the solution for the columns of ; the code does not exploit the zeros of , so the total is flops.
Stability. The computed factors satisfy the backward error bound (Wilkinson; Higham, Theorem 9.3)22 N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, chapters 3 (basics), 8 (triangular systems), 9 (LU) and 10 (Cholesky).
To turn this into a norm bound, let be the growth factor. Every row of has at most entries of magnitude at most , so , and every row of has at most entries bounded by , so
Partial pivoting bounds the growth: since , , so . The bound is attained only by contrived matrices; in practice is small and the method is backward stable. Including the two triangular solves, each computed solution satisfies with (Higham, Theorem 9.5), and the forward error is governed by the condition number :
Each column of the computed inverse obeys this bound.
Closed forms for small determinants
For the determinant is evaluated by formulas instead of LU: the rule , cofactor expansion along the first row for , and for Laplace’s expansion along the first two rows into six products of complementary minors,
where is the complementary pair of columns. The sign is : for and for , which is the pattern in the code.
They use no division and no pivoting decision, which avoids the tolerance test for tiny matrices. Their rounding error is easy to bound: every one of the monomials passes through at most roundings, with for (for : two in each minor, one for their product, five for the sum of six terms), so
The permanent is at least , and much larger when the monomials cancel; then the relative accuracy is lost, exactly as the determinant itself is ill-conditioned there. These formulas are not backward stable in the LU sense.
Rank and reduced row echelon form
rank runs elimination with partial pivoting on a copy and counts pivots
whose magnitude is at least the tolerance, moving to the next column when the
largest remaining entry is below it. This is the numerical rank with an
absolute threshold . It is exact for matrices whose pivots are well
separated from and otherwise depends on scaling. The singular value
decomposition gives the reliable numerical rank, , because
by the Eckart–Young theorem is the 2-norm distance to the nearest
matrix of rank ; elimination pivots have no such meaning, and a matrix with
all pivots of order one can be within of a singular one.33 Kahan’s example: the upper triangular matrix with on the
diagonal and above it has all pivots equal to , while its smallest
singular value decreases like . The
SVD is not implemented.
reduce_row_elimination is Gauss–Jordan elimination: each pivot row is scaled
to make the pivot one, and the pivot column is cleared in every other row. For
each of at most pivots it updates all rows over all
columns, about flops, and works in place. Unlike LU it
produces the reduced form, in which every pivot column is a coordinate vector,
so the non-pivot columns of the result express the dependent columns of in
terms of the pivot columns.
Cholesky factorization
A symmetric positive definite (SPD) matrix has a unique factorization with lower triangular and . Comparing entries of for ,
Each equation determines one new entry from earlier ones, which proves uniqueness once the radicands are positive. The code evaluates them row by row (the Cholesky–Banachiewicz order) and reads only the lower triangle of ; the cost is flops, half of LU, because symmetry halves the work.
Why success characterizes SPD. Write .
Then is an LU factorization without pivoting,
whose pivots are , the radicands. The product of the first
pivots is the leading principal minor , so the radicand at
step equals . By Sylvester’s criterion is SPD
exactly when all leading principal minors are positive, so in exact arithmetic
the factorization succeeds exactly for SPD matrices. With the tolerance,
cholesky_decomposition succeeds exactly when every ratio
exceeds (up to rounding), and
is_positive_definite is implemented by attempting it.
Stability. Cholesky needs no pivoting: from every , so entries cannot grow, and the computed factor satisfies with (Higham, Theorem 10.3). Since up to by the Cauchy–Schwarz inequality, the backward error is small relative to the diagonal of .
Symmetric eigenvalue problem
For real symmetric the spectral theorem gives
with orthogonal and real diagonal. eigen computes it in two
phases for , and by a closed formula for .
Householder tridiagonalization. For , , let and . The reflector is symmetric and orthogonal, and it maps to :
The sign of is opposite to , so adds two
numbers of the same sign and cannot cancel. The code (the tred2 scheme)
works from the last row upwards: for row it reflects
onto its last coordinate, applies from
both sides, and so zeroes row and column outside the tridiagonal band.
After such steps
where is symmetric tridiagonal with diagonal and off-diagonal . The two-sided update costs flops and accumulating explicitly another . Before forming each reflector the row is divided by , which avoids overflow and underflow in ; only an exactly zero row is left unreflected.
Implicit QL with Wilkinson shifts. The tridiagonal is diagonalized by plane rotations. Before each sweep on the unreduced block starting at , the shift is the eigenvalue of the leading block closer to . With , its eigenvalues are
because and the square root equals (the sign of is absorbed by ). The one closer to makes small, that is, takes the sign opposite to :
where the second form follows from for , and avoids the cancellation of the first. The code uses it with . A sweep starts from and applies Givens rotations , , from the bottom of the block upwards, each one chasing the bulge created by the previous; is updated with the same rotations, flops each. The rotation parameters are computed as , , , (or the symmetric form), dividing by the larger of so that no square of a large number is formed.
An off-diagonal entry is treated as zero when it is negligible next to its diagonal neighbours in the working precision,
that is, , and the block then splits. The
test needs no knowledge of , so it works for Float and Double alike, and
it is invariant under scaling of . For symmetric tridiagonal matrices the Wilkinson
shift converges for every input in exact arithmetic (Wilkinson, 1968), and
typically cubically; about two sweeps per eigenvalue is usual. The code
nevertheless aborts after 60 sweeps for one starting index . With
accumulation of the whole computation takes about flops (Golub and
Van Loan’s estimate for the symmetric QR algorithm), of them in
the reduction.
Accuracy. Every transformation is orthogonal, so in exact arithmetic the spectrum never changes, and rounding contributes a backward error of ; setting a negligible to zero perturbs by at most , which is of the same order. Weyl’s inequality, for symmetric and , then gives for the computed eigenvalues
with a modest , independent of the scale of . Eigenvectors are accurate in proportion to , where the gap is the distance to the nearest other eigenvalue (the Davis–Kahan theorem). The only absolute test left is the symmetry check before the computation; the algorithm then reads the lower triangle.
The case. The code works with the symmetric part , . Its characteristic polynomial has the discriminant
a sum of squares, so with and
Computing as instead would subtract two numbers of size and lose about in absolute terms, which for is about : the computed discriminant could even be negative for a diagonal matrix. The code evaluates as with , which cannot overflow, and never thresholds it, so eigenvalues as close as rounding allows stay distinct. The eigenvalue of larger magnitude, , is a sum of two numbers of the same sign and is computed directly; the other follows from , which avoids the cancellation in when . When the matrix is diagonal and the code returns and exactly, in decreasing order, with the coordinate vectors.
For the eigenvector of , both
solve : for the first, , and the second row is ; the second vector is checked the same way. The code takes the first when and the second when , so that or adds numbers of the same sign and cannot cancel. Since is symmetric, the eigenvector of is orthogonal to it, . Each column is scaled so that its entry of largest magnitude is ; the columns are therefore never zero, never parallel, and paired with the right eigenvalues.
Power method
The code starts from , or, if
, from the first coordinate vector
with ; if there is none it returns None.
It then iterates
and stops when ; the normalization makes .
Convergence. If is diagonalizable with eigenvalues and eigenvectors , and has a component along , then
so the direction of converges to linearly with ratio . For negative the sign of alternates, which the Rayleigh quotient does not notice. For symmetric with orthonormal , gives
so the eigenvalue converges twice as fast as the vector. When
with (for example
) the direction oscillates and the residual test never passes, and when
is nilpotent the iterate reaches zero; both cases return None.
What the stopping test guarantees. For symmetric , a residual bounds the distance to the spectrum: expanding in the orthonormal eigenbasis, . With and we have and , so some eigenvalue lies within of the returned . The test is absolute, so for it may be unreachable in floating point (the residual cannot drop below about ), and for it passes before is accurate.
Statistics
variance is the population variance computed in two passes: first the mean
, then . The one-pass formula
subtracts two nearly equal numbers when the
data have a large mean and a small spread, and can even return a negative
value. With and the condition number
of the data, Chan, Golub and LeVeque
(1983) show that the relative error of is bounded by about
for the one-pass formula and by about for the two-pass
one, which is unless is near . The count is
accumulated as a sum of ones in T, exact up to entries for Double
and for Float; beyond that the count stops growing and the mean is
wrong.
Transpose views and products
Let and be the matrices wrapped by the two transpose views. Their logical product is defined when . Its shape is , and the matrix product definition gives, for and ,
The implementation evaluates this sum in the displayed factor order and stores
in the returned Transpose wrapper. It requires only
AddMonoid + Mul: Zero supplies the empty sum when the inner dimension is
zero, and no commutativity or distributivity law for scalar multiplication is
used. The previous shortcut computed , which is generally
different when scalar multiplication is non-commutative. The direct loop takes
scalar multiply-adds and
allocates the output matrix, without copying either input view.
Correctness and invariants
- Storage.
data.length() == row * colat all times; every public accessor checks the row and column separately. - Value-returning methods do not mutate. Only
Unit-returning methods, view writes andreduce_row_eliminationchange a matrix. - Checked/unchecked law.
x.f() == Ok(x.unchecked_f())whenever the precondition holds;inversereturnsErr(SingularMatrix)exactly whenunchecked_inversereturnsNone. - Determinant consistency. For and a matrix that is not
triangular,
determinantreturns exactly0when the LU factorization reports a pivot below , which is also whenis_invertiblereturnsfalseandinversefails; otherwise it returns a product of pivots that are at least in magnitude, which can still underflow. For the closed formulas are used fordeterminant, whileis_invertiblestill uses LU, so a matrix with a tiny non-zero determinant can be “not invertible” with a non-zerodeterminant. - Residual guarantees.
cholesky_decompositionreturns a factor with backward error relative to ;eigenreturns eigenpairs with backward error , for every scale of ;power_methodreturns only pairs with residual at most . - Complexity.
*: flops;determinant: ;inverse: ;rank,reduce_row_elimination: ;cholesky_decomposition: ;eigen: about ;power_method: two matrix-vector products, flops, per iteration; statistics: .
Alternatives rejected
- A relative or norm-scaled tolerance. More robust, but it would change the results of existing callers; deferred until a tolerance policy can be passed explicitly.
- Returning complex eigenvalues. Would make this package depend on a complex number type and change the signature for real symmetric input.
- Copy-on-write views. Would hide the cost of writes and break the in-place contract that views exist for.
- A single portable kernel. Measured to be slower on some targets; the per-target files trade code size for speed while sharing one specification.
Boundaries
mutable does not provide linear solves for a right-hand side as a public
method (only the inverse), QR, SVD or least-squares solvers, eigenvalues of
non-symmetric matrices, sparse storage, condition number estimates, or
scale-aware tolerances. It does not implement the algebra
traits itself; backends/default wraps it for that.
Domain workflows such as regression or optimization belong in downstream
packages.
Footnotes
-
Higham, Lemma 3.1. The proof is an induction on using . ↩
-
N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, chapters 3 (basics), 8 (triangular systems), 9 (LU) and 10 (Cholesky). ↩
-
Kahan’s example: the upper triangular matrix with on the diagonal and above it has all pivots equal to , while its smallest singular value decreases like . ↩