Expand description
Dense linear algebra in pure Rust for real (f64) and complex (Complex<f64>) matrices.
| Operation | Trait | Algorithm |
|---|---|---|
Solve A x = b, inverse, determinant | Solve, Inverse, Factorize, Determinant | LU with partial pivoting |
| Hermitian positive-definite factorisation | Cholesky | Cholesky A = L Lᴴ |
| Triangular systems | SolveTriangular | Forward and back substitution |
| Hermitian / symmetric eigenproblem | Eigh, EigValsh | Householder tridiagonalisation and implicit QL |
| General eigenproblem | Eig, EigVals | Hessenberg reduction and shifted QR (complex Schur form) |
| Singular value decomposition | SVD, SvdJacobi | Golub-Kahan bidiagonalisation; one-sided Jacobi for high relative accuracy |
| Least squares, minimum-norm for rank-deficient systems | LeastSquaresSvd | Householder QR with column pivoting; SVD when rank-deficient |
| Complex Schur form | schur_complex | Hessenberg reduction and shifted QR |
QR (optionally pivoted), RQ, Hessenberg, real Schur, LDLᵀ, polar | qr, rq, hessenberg, schur_real, ldl, polar | Householder reflectors as LAPACK’s; Bunch-Kaufman pivoting |
Generalised eigenproblems A x = λ B x | eigh_generalized, eig_generalized, qz | Cholesky reduction; the QZ algorithm |
| Structured matrices and their solvers | toeplitz, circulant, solve_toeplitz, solve_circulant, solve_banded, solveh_banded, … | Levinson recursion; FFT; band LU and Cholesky |
| General matrix functions, principal angles | funm, subspace_angles | Schur-Parlett; SVDs of orthonormal bases |
| Matrix exponential | expm | Scaling and squaring with Padé approximants |
| Square root, logarithm, fractional powers | sqrtm, logm, fractional_matrix_power | Schur method; inverse scaling and squaring |
| Pseudoinverse, rank, null space, range, norms, condition | pinv, matrix_rank, null_space, orth, norm, cond | From the SVD |
| Sparse matrices: storage, sparse LU, Krylov solvers, a few eigenvalues and singular values | sparse | CSR/CSC; Gilbert-Peierls LU with reverse Cuthill-McKee; CG, MINRES, GMRES, LGMRES, BiCGSTAB, LSQR; Lanczos eigsh, svds; Krylov-Schur eigs |
| Sylvester and Lyapunov equations | solve_sylvester, solve_continuous_lyapunov, solve_discrete_lyapunov | Bartels-Stewart on the complex Schur form |
| Algebraic Riccati equations | solve_continuous_are, solve_discrete_are | Matrix sign function; structure-preserving doubling; Newton refinement |
The traits follow the names and signatures of the ndarray-linalg crate, so code written
against it ports by changing the import. They are implemented for every ndarray
ArrayBase<S, Ix2> (owned arrays and views). Everything is written for clarity and moderate
sizes (up to a few hundred rows); for large problems an optimised LAPACK will be faster. The
benchmarks in crates/linalg_bench compare the two.
See the book chapter Dense linear algebra.
Modules§
- sparse
- Sparse matrices and solvers for large systems, following
scipy.sparseandscipy.sparse.linalg: COO, CSR and CSC storage; a sparse LU factorisation with a fill-reducing column ordering (minimum degree, COLAMD, nested dissection or reverse Cuthill-McKee;spsolve,SparseLu); Krylov solvers (CG, MINRES, GMRES, LGMRES, BiCGSTAB, LSQR) for anyLinearOperator, with Jacobi, incomplete-LU and incomplete-Cholesky preconditioners; a few eigenvalues or singular values by Lanczos methods (eigsh, its shift-invert mode,svds) and of nonsymmetric matrices by Arnoldi’s (eigs,eigs_shift_invert); andexpm_multiply. These are real (f64); complex matrices have their own storage, LU and Krylov solvers (ComplexCsrMatrix,ComplexSparseLu,cg_complex,gmres_complex,bicgstab_complex).
Structs§
- Generalized
Eigen - The solution of the generalised eigenproblem
A x = λ B x. - LdlFactors
- An
LDLᵀ(orLDLᴴ) factorisationA = L D Lᴴwith symmetric pivoting. - Least
Squares Result - The result of
LeastSquaresSvd::least_squares. - LuFactorization
- A factorised square matrix, reusable for many right-hand sides.
- OrdQz
- The result of
ordqz. - OrdQz
Complex - The result of
ordqz_complex. - QrFactors
- A QR factorisation
A P = Q R(Pthe identity without pivoting). - QzFactors
- The generalised complex Schur form
A = Q S Zᴴ,B = Q T Zᴴ. - Real
QzFactors - The real generalised Schur form
A = Q AA Zᵀ,B = Q BB Zᵀ.
Enums§
- Convolution
Mode - Which part of a convolution
convolution_matrixproduces (asnumpy.convolve’smode). - DftScale
- How
dftscales its matrix (SciPy’sscale). - Diag
- Whether a triangular matrix has an implicit unit diagonal.
- Eigen
Sort - Which eigenvalues
schur_sorted,schur_sorted_complex,ordqzandordqz_complexmove to the top left, as SciPy’ssortargument. - Linalg
Error - Why a decomposition or solve failed. Converts into the library-wide
ErrorsJSLwith?. - Norm
- Which matrix norm
normcomputes (NumPy’sord). - Pascal
Kind - Which Pascal matrix (SciPy’s
kind). - QrMode
- How much of a QR (or RQ) factorisation to return (SciPy’s
mode). - UPLO
- Which triangle of a matrix to use (or produce).
Traits§
- Cholesky
- The Cholesky factor of a Hermitian positive-definite matrix whose
uplotriangle is read: lowerLwithA = L LᴴforUPLO::Lower, upperU = LᴴforUPLO::Upper. - Determinant
- The determinant of a square matrix.
- Eig
- Eigenvalues and unit eigenvectors (columns) of a general square matrix, both complex.
- EigVals
- Eigenvalues of a general square matrix.
- EigValsh
- Eigenvalues (ascending) of a Hermitian matrix.
- Eigh
- Eigenvalues (ascending) and orthonormal eigenvectors (columns) of a Hermitian matrix whose
uplotriangle is read. - Factorize
- An LU factorisation to solve many systems with the same matrix.
- Inverse
- The inverse of a square matrix.
- Least
Squares Svd - The minimum-norm least-squares solution of
A x ≈ b, robust to rank deficiency. - SVD
- The singular value decomposition
A = U Σ Vᴴ:(U, σ, Vᴴ)with the full square unitary factors when requested and themin(m, n)singular values in descending order. - Scalar
- A real or complex double-precision scalar.
- Solve
- Solves
A x = bfor squareAby LU with partial pivoting. - Solve
Triangular - Solves
T X = Bfor a triangularT(only theuplotriangle is read) and a right-hand side that is a vector or a matrix. - SvdJacobi
- The SVD by the one-sided Jacobi method, with the same output as
SVD::svd. It is slower than the default (Golub-Kahan) method but determines small singular values to high relative accuracy, which matters for graded or badly scaled matrices.
Functions§
- block_
diag - The block diagonal matrix with the given blocks (SciPy’s
block_diag). - circulant
- The circulant matrix with first column
c(SciPy’scirculant):C[i, j] = c[(i − j) mod n]. - companion
- The companion matrix of the polynomial
a[0] xⁿ + a[1] xⁿ⁻¹ + … + a[n](SciPy’scompanion): first row−a[1..]/a[0], ones on the subdiagonal. Its eigenvalues are the polynomial’s roots. - cond
- The condition number
‖A‖ ‖A⁻¹‖in the given norm (NumPy’scond); for the 2-norm,σ_max / σ_min, which is also defined for rectangular matrices. Infinite for singular matrices. - convolution_
matrix - The matrix
MwithM v = convolve(a, v)for vectorsvof lengthn(SciPy’sconvolution_matrix). - dft
- The discrete Fourier transform matrix
W[j, k] = ω^{jk},ω = e^{−2πi/n}(SciPy’sdft). - eig_
generalized - The generalised eigenvalues and right eigenvectors of
(A, B)(SciPy’seig(a, b)), from the QZ form: for eachk,(β_k S − α_k T) y = 0is solved by back substitution withy_k = 1, andx = Z yis normalised to unit length. - eigh_
generalized - The eigenvalues (ascending) and eigenvectors of the symmetric-definite problem
A x = λ B x,AHermitian andBHermitian positive definite (SciPy’seigh(a, b), LAPACK’ssygvtype 1). WithB = L Lᴴ, the problem becomes the standardC y = λ yforC = L⁻¹ A L⁻ᴴ, andx = L⁻ᴴ y; the eigenvectors areB-orthonormal,Xᴴ B X = I. - expm
- The matrix exponential
eᴬ = I + A + A²/2! + …(SciPy’slinalg.expm). - fiedler
- The Fiedler matrix
|a_i − a_j|(SciPy’sfiedler). - fractional_
matrix_ power A^p = exp(p log A)for realp(SciPy’sfractional_matrix_power, by this route rather than its Schur-Padé algorithm).- funm
f(A)for a scalar functionf(SciPy’sfunm), by the Schur-Parlett method: with the complex Schur formA = Z T Zᴴ,F = f(T)is upper triangular withF_ii = f(T_ii), and the commutationT F = F Tdetermines the rest, superdiagonal by superdiagonal:F_ij = (T_ij (F_jj − F_ii) + Σ_{i<k<j} (T_ik F_kj − F_ik T_kj)) / (T_jj − T_ii). Returns(Z F Zᴴ, error estimate); the estimate is large when eigenvalues nearly coincide, where this recurrence divides by small differences.- hadamard
- The
n × nHadamard matrix of ±1 entries by Sylvester’s construction (SciPy’shadamard);nmust be a power of two. Its rows are orthogonal:H Hᵀ = n I. - hankel
- The Hankel matrix with first column
cand last rowr(SciPy’shankel);r[0]is ignored. Withoutr, the entries below the anti-diagonal are zero. - hessenberg
- The Hessenberg form
A = Q H Qᴴ(SciPy’shessenbergwithcalc_q=True; LAPACK’sgehd2andorghr):His zero below its first subdiagonal,Qunitary. Reflectorizeros columnibelow rowi + 1and is applied from both sides. Returns(H, Q). - hilbert
- The Hilbert matrix
1/(i + j + 1)(SciPy’shilbert), a classic ill-conditioned test matrix. - invhilbert
- The exact inverse of the Hilbert matrix (SciPy’s
invhilbert), from its closed form(−1)^{i+j} (i + j + 1) binom(n+i, n−j−1) binom(n+j, n−i−1) binom(i+j, i)²; the integer entries are exact forn ≤ 14. - invpascal
- The inverse of the Pascal matrix (SciPy’s
invpascal): integer entries,(−1)^{i+j} binom(i, j)for the triangular kinds, and their product for the symmetric one. - ldl
- The Bunch-Kaufman factorisation of a symmetric or Hermitian matrix (SciPy’s
ldl, LAPACK’ssytf2/hetf2):A = L D Lᴴ(orU D Uᴴwithlower = false),Dblock diagonal with 1 × 1 and 2 × 2 blocks, andLa row permutation of a unit triangular matrix. A 2 × 2 pivot is taken when no diagonal entry is large enough relative to its column,α = (1 + √17)/8, which bounds the growth of the entries for indefinite matrices. Only thelower(or upper) triangle is read;hermitian = falsefactorises a complex symmetric matrix,A = L D Lᵀ. - leslie
- The Leslie matrix of a population model (SciPy’s
leslie): fecunditiesf(lengthn) on the first row, survival ratess(lengthn − 1) on the subdiagonal. - logm
- The principal logarithm
Lwithe^L = Aand eigenvalues with imaginary parts in(−π, π)(SciPy’slogm), by the inverse scaling and squaring method on the Schur form: take square roots ofTuntil‖T − I‖₁ ≤ 0.25(ktimes), evaluatelog(I + X)by the[8/8]Padé approximant written as Gauss-Legendre quadrature,Σ wⱼ X (I + xⱼ X)⁻¹, and multiply by2ᵏ. - matrix_
rank - The numerical rank: the number of singular values above
tol(NumPy’s defaultσ_max · max(m, n) · εwhenNone). - norm
- A matrix norm (or, for the
Minusvariants, the corresponding minimum), as NumPy’snorm. - null_
space - An orthonormal basis of the null space of
A, as columns (SciPy’snull_space): the right singular vectors of the singular values at mostrcond · σ_max(defaultmax(m, n) ε). - ordqz
- The real generalised Schur form with the eigenvalues selected by
sortleading (SciPy’sordqz(a, b, sort=..., output='real')):qz_real, then adjacent block swaps (LAPACK’sdtgsen/dtgexc) built from the generalised Sylvester equationA₁₁R − L A₂₂ = −A₁₂,B₁₁R − L B₂₂ = −B₁₂, whose solution spans the deflating subspaces of the lower block. - ordqz_
complex - The complex generalised Schur form with the selected eigenvalues leading (SciPy’s
ordqz(..., output='complex')):qz, then swaps of adjacent 1 × 1 blocks from the generalised Sylvester equation (LAPACK’sztgexc). - orth
- An orthonormal basis of the range (column space) of
A, as columns (SciPy’sorth). - pascal
- The Pascal matrix (SciPy’s
pascal,exact=False): binomial coefficients, exact while they are below 2⁵³. - pinv
- The Moore-Penrose pseudoinverse
A⁺ = V Σ⁺ Uᴴ(SciPy’spinv): singular values at mostrtol · σ_maxare treated as zero, withrtol = max(m, n) εby default. - polar
- The polar decomposition
A = U P(side = right) orA = P U(left) (SciPy’spolar):Uwith orthonormal columns (or rows) andPHermitian positive semi-definite, from the SVDA = W Σ Vᴴ:U = W Vᴴ, andP = V Σ VᴴorW Σ Wᴴ. Returns(U, P). - qr
- The QR factorisation
A P = Q R(SciPy’sqr, withpivotingitspivoting=True):Qhas orthonormal columns,Ris upper triangular (trapezoidal), and with pivoting the columns are chosen in order of largest remaining norm, so that|R₁₁| ≥ |R₂₂| ≥ …, which reveals the rank. - qz
- The generalised complex Schur form of the pencil
(A, B)(SciPy’sqz(a, b, output='complex')): unitaryQ,ZwithQᴴ A Z = S,Qᴴ B Z = Tupper triangular. The generalised eigenvalues areS_ii / T_ii(infinite whereT_ii = 0).Bis first made triangular by a QR factorisation andAHessenberg by Givens rotations that keepBtriangular; then QZ sweeps with Wilkinson-type shifts chase a bulge down the pencil until the subdiagonal ofSvanishes. A zero on the diagonal ofT(an infinite eigenvalue) is chased to the bottom and deflated. - qz_real
- The real generalised Schur form of the pencil
(A, B)(SciPy’sqz(a, b, output='real')): orthogonalQ,ZwithQᵀ A Z = AAquasi upper triangular andQᵀ B Z = BBupper triangular.Bis made triangular by a QR factorisation andAHessenberg by Givens rotations that keepBtriangular; then Moler and Stewart’s implicit double-shift QZ sweeps — the Francis step applied toA B⁻¹without forming it — chase bulges down the pencil untilAis quasi-triangular. A zero on the diagonal ofB(an infinite eigenvalue) is chased to the bottom of the active window and deflated. 2 × 2 blocks with real eigenvalues are split. - rq
- The RQ factorisation
A = R Q(SciPy’srq, LAPACK’sgerq2):Rupper triangular (trapezoidal, aligned to the right),Qwith orthonormal rows. Each step reflects a row, from the last upwards, onto its own last allowed column. Returns(R, Q). - schur_
complex - The complex Schur form
A = Z T Zᴴ:Tupper triangular with the eigenvalues ofAon its diagonal,Zunitary (SciPy’slinalg.schur(a, output='complex')). Returns(T, Z). - schur_
real - The real Schur form
A = Z T Zᵀof a real matrix (SciPy’sschur(a, output='real')):Zorthogonal andTquasi upper triangular, with 1 × 1 blocks for real eigenvalues and 2 × 2 blocks[a b; c a],b c < 0, for each complex conjugate paira ± i√(−bc). Returns(T, Z). - schur_
sorted - The real Schur form
A = Z T Zᵀwith the eigenvalues selected bysortin the leadingsdimpositions (SciPy’sschur(a, output='real', sort=...)). A complex pair is selected when either member is. The selected blocks are moved up one adjacent swap at a time (LAPACK’sdtrsen/dtrexc). Returns(T, Z, sdim). - schur_
sorted_ complex - The complex Schur form
A = Z T Zᴴwith the eigenvalues selected bysortfirst (SciPy’sschur(a, output='complex', sort=...)), by adjacent swaps of 1 × 1 blocks (LAPACK’sztrexc). Returns(T, Z, sdim). - solve_
banded - Solves
A x = bfor a bandedAwithlsubdiagonals andusuperdiagonals, given in LAPACK band storageab[u + i − j, j] = A[i, j](SciPy’ssolve_banded((l, u), ab, b)), by Gaussian elimination with partial pivoting within the band (LAPACK’sgbsv):O(n l (l + u))operations. Row interchanges widen the upper band ofUtol + u. - solve_
circulant - Solves
C x = bfor the circulant matrixCwith first columncinO(n log n)(SciPy’ssolve_circulant): the DFT diagonalises every circulant matrix,C = F⁻¹ diag(F c) F, sox = F⁻¹ (F b / F c). An error is returned when some|F c|is belowtol(defaultn ε max |F c|), whereCis numerically singular. - solve_
continuous_ are - Solves the continuous algebraic Riccati equation
Aᴴ X + X A − X B R⁻¹ Bᴴ X + Q = 0for the stabilising solutionX(SciPy’slinalg.solve_continuous_are, without itseandsoptions), for whichA − B R⁻¹ Bᴴ Xhas all its eigenvalues in the left half-plane. - solve_
continuous_ lyapunov - Solves the continuous Lyapunov equation
A X + X Aᴴ = Q(SciPy’slinalg.solve_continuous_lyapunov). For a stableAandQ = −C Cᴴ,Xis the controllability Gramian. - solve_
discrete_ are - Solves the discrete algebraic Riccati equation
Aᴴ X A − X − Aᴴ X B (R + Bᴴ X B)⁻¹ Bᴴ X A + Q = 0for the stabilising solution (SciPy’slinalg.solve_discrete_are, without itseandsoptions), for whichA − B KwithK = (R + Bᴴ X B)⁻¹ Bᴴ X Ahas all its eigenvalues inside the unit circle. - solve_
discrete_ lyapunov - Solves the discrete Lyapunov equation
A X Aᴴ − X + Q = 0(SciPy’slinalg.solve_discrete_lyapunov). The solution is unique when no product of two eigenvalues ofA(one conjugated) equals 1; forAwith spectral radius below 1 andQ = B Bᴴ,Xis the controllability GramianΣ Aᵏ B Bᴴ (Aᴴ)ᵏ. - solve_
sylvester - Solves the Sylvester equation
A X + X B = QforX(SciPy’slinalg.solve_sylvester), withAn × n,Bm × mandQn × m. The solution is unique when no eigenvalue ofAis the negative of an eigenvalue ofB; otherwiseLinalgError::Singularis returned. - solve_
toeplitz - Solves
T x = bfor the Toeplitz matrixTwith first columncand first rowr(defaultconj(c)) by Levinson recursion inO(n²)operations (SciPy’ssolve_toeplitz, after the classictoeplz). The recursion builds the solutions for the leadingm × msections one size at a time, together with those of two auxiliary systems for the reversed sections; it needs every leading principal minor to be non-singular, and is not stable for indefinite or badly conditionedT(then usesolve). - solveh_
banded - Solves
A x = bfor a Hermitian positive definite bandedA(SciPy’ssolveh_banded, LAPACK’spbsv) by the band Cholesky factorisationA = L Lᴴ, which keeps the bandwidthw:O(n w²)operations.abhasw + 1rows; withlower = false(SciPy’s default) it holds the upper triangle,ab[w + i − j, j] = A[i, j]fori ≤ j, and withlower = truethe lower one,ab[i − j, j] = A[i, j]fori ≥ j. - sqrtm
- The principal square root
XwithX² = Aand eigenvalues in the right half-plane (SciPy’ssqrtm), by the Schur method:A = Z T Zᴴ,X = Z R ZᴴwithR² = Ttriangular. Matrices with eigenvalues on the closed negative real axis have no principal square root; zero eigenvalues of multiplicity above one make it fail. - subspace_
angles - The principal angles between the column spaces of
AandB(SciPy’ssubspace_angles), largest first. With orthonormal basesQ_A,Q_B, the cosines are the singular values ofQ_Aᴴ Q_B; angles whose cosine exceeds1/√2are taken instead from the sines, the singular values ofQ_B − Q_A Q_Aᴴ Q_B, which keeps small angles accurate (Knyazev and Argentati, 2002). - toeplitz
- The Toeplitz matrix with first column
cand first rowr(SciPy’stoeplitz);r[0]is ignored. Withoutr, the matrix is Hermitian:r = conj(c).
Type Aliases§
- Complex
Eigen - Complex eigenvalues and eigenvectors (as columns).
- Complex
Schur - A complex Schur form
(T, Z)withA = Z T Zᴴ. - Result