Learn/Numerics/Linear Algebra and Polynomials

Linear Algebra and Polynomials

Solve systems of equations, factor and decompose matrices, find eigenvalues, and work with polynomials from a script.

Time29 min readLevelIntermediateUpdatedUpdated Nov 2026
Script language

01Overview

What It Covers

Linear algebra is the arithmetic of matrices: solving A x = b, measuring how a matrix stretches space, and breaking a matrix into simpler parts. Polynomials are the other half of this page: building them, finding their roots and fitting them to data.

The routines here are mldivide, inv, det, rank, null, orth, pinv, norm, cond, lu, qr, chol, svd, eig, schur and its relatives, expm, logm, sqrtm, kron, sylvester, lyap, dlyap, poly, roots, polyval, polyfit, conv, deconv, polyder, polyint and residue. Each routine has a row in the MATLAB name table.

Luau reaches 11 of these routines: solve, inv, det, expm, eig, eigvals, svd, singular_values, roots, polyfit and polyval. Rune reaches those 11 and 35 more: lstsq, rank, null, orth, pinv, norm, vec_norm, cond, lu, qr, qr_thin, chol, generalized_eigvals, schur, schur_complex, ordschur, rsf2csf, hess, logm, logm_real, sqrtm, sqrtm_real, kron, sylvester, lyap, dlyap, poly, poly_real, charpoly, conv, deconv, polyadd, polyder, polyint and residue. rank, null and orth also have the forms rank_with, null_with and orth_with, which take options. The rest are part of the Rust crate eustress-numerics and no script calls them: eig_sym, svd_thin, solve_vec, solve_owned, solve_complex and polyval_c. A script calls Numerics.solve(...)numerics::solve(...)?; Your First Call on the Numerics page covers Luau and Rune once.

Matrices and Shape Rules

Every matrix on this page is dense and real unless the text says complex. See Matrices, Vectors and Models for the conventions that hold on every page.

In a script a matrix is an array of rows: {{2, 1}, {1, 3}}[[2.0, 1.0], [1.0, 3.0]]. A vector is an array. Luau arrays start at 1. Rune arrays start at 0. Rows of different lengths are an error.

Shape rules differ by routine.

  • Any shape: solve, lstsq, rank, null, orth, pinv, norm, cond, lu, qr and svd.
  • Square only: inv, det, chol, eig, eigvals, eig_sym, schur, hess, expm, logm and sqrtm. A non-square matrix raises a not-square error.
  • Two square matrices of the same size: the generalized eigenvalue routine takes A and B.
  • Square plus a matching right side: sylvester takes square A and B and a C with as many rows as A and as many columns as B. lyap and dlyap take a square A and a Q of the same size.

The solvers and factorizations reject a matrix that has NaN or infinite entries with an invalid-argument error. Empty matrices are handled: the determinant of a 0 by 0 matrix is 1, and its eigenvalue list is empty.

02Solving Systems

Square Systems

solve is MATLAB's mldivide: it solves A X = B. For a square A it uses LU factorization with partial pivoting. B can hold several right-hand sides as columns, and X has one column per column of B. solve_vec solves for a single right-hand side. solve_owned takes both matrices by value; for one right-hand side and 128 unknowns or more it factors A in place and overwrites B with no copy, and smaller systems take another route. The solution is the same. solve_complex does the same for a complex square system.

The routine takes no tolerance. A matrix is singular for solve in two cases: an exactly zero pivot in the LU factor, which raises singular matrix: solve: matrix is exactly singular, and a result with NaN or infinite entries from finite input, which raises singular matrix: solve: matrix is numerically singular. A NaN or infinite input entry raises an invalid-argument error. A B whose row count differs from A raises dimension mismatch: solve: A is (3, 3), B is (2, 1).

A nearly singular matrix that is not exactly singular returns an answer. Check cond before you trust it; see Singular and Ill-Conditioned Input.

Luau and Rune reach solve. solve_vec, solve_owned and solve_complex are part of the Rust crate only. A script calls solve(A, b) with the matrix first. A vector b gives a vector x, which is what solve_vec returns. A matrix b gives a matrix X with one column per column of b. A singular matrix is an error a script can catch; the message is the one above after the prefix Numerics.solve: numerics::solve: as described under Errors on the Numerics page.

This solves 2x + y = 5 and x + 3y = 6:

Luau
local x = Numerics.solve({{2, 1}, {1, 3}}, {5, 6})
print(x[1], x[2])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let x = numerics::solve([[2.0, 1.0], [1.0, 3.0]], [5.0, 6.0])?;
    let first = x[0];
    let second = x[1];
    log_info(`x = ${first}, ${second}`);
}

The result is the array 1.8, 1.4 in both languages. The tests check both values to within 1e-12.

Over- and Underdetermined Systems

When A is not square, solve hands the system to lstsq, which returns the least-squares solution. For a tall A of full column rank, lstsq uses a QR factorization with column pivoting. It tests the rank with a tolerance of max(rows, columns) times machine epsilon times the leading diagonal entry of R.

A wide A, or a rank-deficient A, takes a different route: lstsq multiplies B by the pseudoinverse pinv of A. The result is the minimum-norm least-squares solution, the one of smallest length among all that minimize the residual. MATLAB returns a basic solution in that case. The residual is the same; the solution vector can differ. This matches MATLAB's lsqminnorm.

Luau reaches this through solve: a non-square A gives the least-squares solution. Rune also calls lstsq(A, b) itself, with a vector or a matrix for b. This script fits the line through the points (0, 1), (1, 2) and (2, 2):

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let fit = numerics::lstsq([[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]], [1.0, 2.0, 2.0])?;
    log_info(`${fit[0]}, ${fit[1]}`);
}

The normal equations give the intercept 7/6 and the slope 1/2, to within rounding.

Inverse and Determinant

inv needs a square matrix. It computes the inverse as the solution of A X = I, so it fails in the same cases as solve and with the same messages. det returns the determinant of a square matrix as one number.

Luau and Rune reach both. inv(A) returns a matrix of rows and det(A) returns a number.

Luau
local A = {{1, 2}, {3, 4}}
print(Numerics.det(A))
local B = Numerics.inv(A)
print(B[1][1], B[1][2], B[2][1], B[2][2])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let a = [[1.0, 2.0], [3.0, 4.0]];
    let d = numerics::det(a)?;
    let b = numerics::inv(a)?;
    log_info(`det = ${d}`);
    log_info(`inverse row 0 = ${b[0][0]}, ${b[0][1]}`);
}

The determinant is 1 times 4 minus 2 times 3, which is -2, to within rounding. The inverse is the matrix with rows -2, 1 and 1.5, -0.5.

03Rank, Null Space and Conditioning

Rank, Null Space and Range

All three read the singular values of A. rank counts the singular values above a tolerance. null returns an orthonormal basis of the null space as columns: the right singular vectors that belong to the singular values at or below the tolerance, so it has n minus rank columns for an m by n matrix. orth returns an orthonormal basis of the range as columns: the left singular vectors that belong to the singular values above the tolerance.

Each of the three accepts a tolerance that replaces the default.

RoutineDefault tolerance
rank, null, orth, pinvmax(m, n) times machine epsilon times the largest singular value

Rune reaches rank, null and orth; Luau does not. A Rune script replaces the tolerance with the option tol in the _with form: rank_with(A, #{tol: 10.0}), null_with and orth_with take the same object. For the matrix with rows 1, 2 and 2, 4 the singular values are 5 and 0, so rank is 1 and rank_with with tol 10 is 0. rank returns a whole number, and null and orth return a matrix of rows with one basis vector per column. To count the rank from a Luau script, call singular_values and count the values above the tolerance in the table.

The Pseudoinverse

pinv returns the Moore-Penrose pseudoinverse, computed from the economy SVD. Singular values at or below the default tolerance count as zero: their reciprocals are set to zero instead of being inverted. pinv takes no tolerance argument.

Rune reaches pinv; Luau does not. For a system A x = b, pinv of A times b is the minimum-norm least-squares solution. It is the same solution that lstsq returns for a wide or rank-deficient A.

Norms and Condition Number

norm takes a matrix and a kind:

  • the 1-norm, the largest column sum;
  • the 2-norm, the largest singular value;
  • the infinity norm, the largest row sum;
  • the Frobenius norm.

vec_norm returns the Euclidean norm of a vector, computed with scaling so the intermediate squares do not overflow. cond returns the 2-norm condition number: the largest singular value divided by the smallest. It is infinite for a singular matrix.

Rune reaches norm, vec_norm and cond; Luau does not. The kind is the second argument of norm: the number 1, the number 2, the text "inf" or the text "fro". The first value of singular_values is the 2-norm, because the values come largest first, and the first divided by the last is the condition number.

04Factorizations

A factorization writes a matrix as a product of simpler matrices. The diagram shows the shape of each product on this page. Luau and Rune reach svd, singular_values, eig and eigvals from this section. Rune also reaches lu, qr, qr_thin, chol, generalized_eigvals, schur, schur_complex, rsf2csf, ordschur and hess. svd_thin and eig_sym are part of the Rust crate and no script calls them.

LUPA=LUP permutation, L unit lower, U upperQRA=QRQ orthogonal and square, R upperCholeskyA=R'RA symmetric positive definiteSVDA=USV'S: singular values, largest firstEigenAV=VDV columns: unit-length eigenvectorsSchurA=UTU'T has 1 by 1 and 2 by 2 blocks
Each factorization writes A as a product. Triangular factors are drawn as triangles. Orthogonal and orthonormal factors are violet, and A is the accented box.

LU

lu returns three matrices: L, a unit lower-triangular factor; U, an upper-triangular factor; and P, a row permutation written as a square matrix. They satisfy P A = L U. The pivoting is partial pivoting: at each step the row with the largest entry in the column moves up. A singular A is not an error here; the routine returns the factors.

Rune reaches lu and returns an object with the matrices l, u and p; Luau does not. This script reads U:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let f = numerics::lu([[4.0, 3.0], [6.0, 3.0]])?;
    let u = f["u"];
    log_info(`${u[0][0]}, ${u[0][1]}, ${u[1][0]}, ${u[1][1]}`);
}

The second row has the larger entry in the first column, so partial pivoting moves it up. U has the rows 6, 3 and 0, 1, to within rounding, and l[1][0] is 2/3.

QR

qr returns Q and R with A = Q R, where Q is square and orthogonal and R has the shape of A with zeros below the diagonal. qr_thin returns the economy form: Q keeps its first min(m, n) columns and R keeps its first min(m, n) rows. Neither routine returns a column permutation. Rune reaches both, and each returns an object with the matrices q and r.

Cholesky

chol returns the upper-triangular R with R' R = A, for a symmetric positive definite A. A matrix that is not square raises a not-square error. A matrix that is not symmetric raises not positive definite: chol: matrix is not symmetric, and a symmetric matrix that is not positive definite raises not positive definite: chol: matrix is not positive definite. Rune reaches chol and returns R as a matrix of rows.

Singular Value Decomposition

svd returns U, the singular values S and V with A = U diag(S) V'. The columns of U and V are orthonormal. The singular values come back as a vector, largest first. For an m by n matrix the full form returns a square U (m by m) and a square V (n by n). svd_thin returns the economy form. singular_values returns the values only, largest first. It reduces the matrix to bidiagonal form and runs a dqds iteration on the bidiagonal, which costs of order n squared; a bidiagonal with a zero on its diagonal uses an implicit-shift QR iteration instead. svd and svd_thin run a divide-and-conquer method on the bidiagonal, written in this crate, and fall back to a different SVD for a matrix more than 11/6 times taller than wide (or the reverse) and for any case where the divide and conquer does not finish.

If the iteration does not converge the routine raises no convergence: svd: the iteration did not converge.

On accuracy, SciPy's residual for the full SVD is the smaller one. The scaled residual of the factorization is 2.76e-15 for the library and 2.59e-15 for SciPy on a 300 by 300 matrix, and 4.31e-15 against 3.58e-15 on a 1000 by 1000 matrix. Both are at rounding level; SciPy's is the smaller number by a factor of 1.07 and 1.20.

svd is the one kernel whose bits differ between one thread and several; see Bit-for-Bit Results.

Luau and Rune reach svd and singular_values. svd(A) returns the fields u, s and v: u and v are matrices of rows whose columns are the singular vectors, and s is an array, largest first. svd_thin is Rust only: no script calls it. A diagonal matrix has its absolute diagonal entries as singular values:

Luau
local s = Numerics.singular_values({{3, 0}, {0, 4}})
print(s[1], s[2])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let s = numerics::singular_values([[3.0, 0.0], [0.0, 4.0]])?;
    log_info(`${s[0]}, ${s[1]}`);
}

The script prints 4 and 3, to within rounding.

Eigenvalues and Eigenvectors

eig works on a general real square matrix. It returns the eigenvalues, complex in general, and the right eigenvectors as columns, so that A V = V diag(values). Each eigenvector has unit 2-norm. eigvals returns the eigenvalues only.

Luau and Rune reach eig and eigvals. Both return complex values as two arrays: eigvals(A) returns {re = {...}, im = {...}}#{re: [...], im: [...]}. eig(A) returns the fields values, in that form, and vectors, a pair re and im of matrices of rows with one eigenvector per column. eig_sym is Rust only. generalized_eigvals is Rune only: generalized_eigvals(A, B) returns an object with the fields alpha and beta, each in the same two-array form.

Luau
local e = Numerics.eig({{0, 1}, {-1, 0}})
print(e.values.re[1], e.values.im[1])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let e = numerics::eig([[0.0, 1.0], [-1.0, 0.0]])?;
    let values = e["values"];
    let re = values["re"];
    let im = values["im"];
    log_info(`${re[0]}, ${im[0]}`);
}

The characteristic polynomial of this matrix is s squared plus 1, so its eigenvalues are the conjugate pair i and -i. Which of the two comes first is the Schur order, so the real part printed is 0 to within rounding and the imaginary part printed is 1 or -1.

eig_sym is for a symmetric matrix. It reads only the lower triangle, returns real eigenvalues in ascending order, and returns orthonormal real eigenvectors.

The generalized problem A x = lambda B x is covered for eigenvalues only. generalized_eigvals takes A and B and returns each eigenvalue as a pair (alpha, beta), with lambda equal to alpha divided by beta. The generalized eigenvectors are not covered.

The Schur QR iteration is written in this crate and serves every matrix order; faer's eigensolver is used only if the iteration does not converge. The eigenvalues come in Schur order, the order along the diagonal of the Schur form, not sorted. There is no balancing, so the routine is the counterpart of MATLAB's eig(A, 'nobalance'). If the iteration does not converge in both solvers, eig raises no convergence: eig: the QR iteration did not converge.

Four hard fixtures of order 80 test the solver against SciPy. Perturbation theory limits any solver on the defective matrix, so its error is measured against the exact eigenvalues. The residual is the scaled residual of the eigenvector equation.

MatrixEigenvalue error: library / SciPyResidual: library / SciPy
Defective: Jordan blocks of order 4, 3 and 2, rotated1.69e-5 / 2.05e-5, against the exact values3.35e-16 / 3.72e-16
Clustered and normal: 16 equal eigenvalues, 16 spaced 1e-9, 8 complex pairs spaced 1e-73.63e-15 / 3.13e-15, against the exact values3.19e-16 / 3.34e-16
Graded over twelve decades2.46e-15 from SciPy's values1.89e-16 / 2.79e-16
Cyclic permutation (roots of unity)5.33e-15 / 7.63e-15, against the exact values5.12e-16 / 6.82e-16

On the clustered fixture SciPy's eigenvalue error is the smaller one: 3.63e-15 for the library against 3.13e-15, about 1.16 times larger. Both are about 16 rounding units of the matrix norm. The library's residual on the same matrix is the lower of the two. On the defective and cyclic fixtures the library's eigenvalue error is the smaller, and its residual is the lower on all four.

The figure shows the seven eigenvalues of the 7 by 7 matrix eig_general from the linear algebra fixture. They form three conjugate pairs and one real value, -1.4949. The pair 1.0865 plus and minus 0.7733 i has a positive real part, so a continuous-time system with this matrix is unstable.

-2-1012-2-1012imaginary partreal part2 with a positive real part5 with a negative real partimaginary axisBoth axes use the same scale.
The eigenvalues of the 7 by 7 matrix eig_general in tests/fixtures/linalg.json, drawn from linalg_eigenvalues.csv, real output of the library. Complex eigenvalues of a real matrix come in conjugate pairs, so the plot is symmetric about the real axis. Points right of the dashed imaginary axis have a positive real part.

Schur and Hessenberg Forms

schur returns the real Schur form: an orthogonal U and a quasi upper-triangular T with A = U T U'. T has 1 by 1 blocks on the diagonal for real eigenvalues and 2 by 2 blocks, with equal diagonal entries, for complex pairs. schur_complex returns the complex Schur form, with an upper-triangular T whose diagonal holds the eigenvalues. rsf2csf converts a real form to a complex one.

ordschur reorders a real Schur form so that the eigenvalues you select come first, and returns the reordered form together with the number of eigenvalues selected. The selection rule must give the same answer for both members of a complex pair. If two blocks share an eigenvalue and cannot be swapped, it raises no solution: ordschur: two blocks share an eigenvalue and cannot be swapped.

hess returns Q and H with A = Q H Q', where H is upper Hessenberg.

Rune reaches schur, schur_complex, rsf2csf, ordschur and hess; Luau does not. schur returns an object with the matrices u and t. schur_complex and rsf2csf return u and t each as a pair of arrays re and im of rows. ordschur(U, T, select) takes a function |re, im| that returns true for an eigenvalue to move first, and returns u, t and count. hess returns q and h.

05Matrix Functions and Equations

Matrix Exponential

expm computes the matrix exponential of a square matrix by scaling and squaring with a Pade approximant (Higham). It returns a real matrix. The c2d routine uses it for the zoh and foh methods. One test compares it with SciPy; a second compares it with the closed form for a rotation generator.

Luau reaches expm and no other routine of this section. Rune also reaches logm, logm_real, sqrtm, sqrtm_real, kron, sylvester, lyap and dlyap. expm(A) returns a matrix of rows. For the nilpotent matrix with rows 0, 1 and 0, 0 the square is zero, so the exponential is the identity plus the matrix:

Luau
local E = Numerics.expm({{0, 1}, {0, 0}})
print(E[1][1], E[1][2], E[2][1], E[2][2])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let e = numerics::expm([[0.0, 1.0], [0.0, 0.0]])?;
    log_info(`${e[0][0]}, ${e[0][1]}, ${e[1][0]}, ${e[1][1]}`);
}

The script prints 1, 1, 0, 1, to within rounding.

Matrix Logarithm and Square Root

logm returns the principal matrix logarithm, and sqrtm the principal matrix square root. Both work on the complex Schur form and return a complex matrix, because the result is complex in general: the square root is complex when the matrix has negative real eigenvalues.

logm_real and sqrtm_real return a real matrix and raise a no-solution error (for example no solution: sqrtm_real: the result is not real) when the principal result is complex. A singular matrix has no logarithm: logm raises singular matrix: logm: the matrix is singular. sqrtm raises a singular-matrix error for a matrix with a defective zero eigenvalue, which has no square root. logm and sqrtm return an object with the fields re and im, each a matrix of rows, and logm_real and sqrtm_real return a matrix of rows.

Kronecker Product

kron returns the Kronecker product of A and B: the block matrix in which each entry of A multiplies a whole copy of B. For an A that is p by q and a B that is r by s, the result is (p r) by (q s). It accepts any shapes and raises no errors. Rune reaches it as kron(A, B).

Sylvester and Lyapunov Equations

  • sylvester solves A X + X B = C.
  • lyap solves the continuous Lyapunov equation A X + X A' + Q = 0.
  • dlyap solves the discrete Lyapunov (Stein) equation A X A' - X + Q = 0.

All three solve on the complex Schur form and return a real X. When the equation has no unique solution they raise a singular-matrix error: singular matrix: sylvester: A and -B share an eigenvalue, singular matrix: lyap: A has eigenvalues that sum to zero and singular matrix: dlyap: A has eigenvalue pairs with product 1. The generalized forms with an E matrix are not covered. The gram routine on the control page uses lyap for continuous models and dlyap for discrete ones. Luau does not reach sylvester, lyap or dlyap.Rune calls sylvester(A, B, C), lyap(A, Q) and dlyap(A, Q) with matrices of rows and gets X back as a matrix of rows. This script solves A X + X B = C with A holding 1 and 2 on its diagonal, B equal to 3 and C the column 8, 10:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let x = numerics::sylvester([[1.0, 0.0], [0.0, 2.0]], [[3.0]], [[8.0], [10.0]])?;
    log_info(`${x[0][0]}, ${x[1][0]}`);
}

Row by row the equation reads (1 + 3) x1 = 8 and (2 + 3) x2 = 10, so both entries print 2, to within rounding.

06Polynomials

How a Polynomial Is Written

A polynomial is a list of coefficients with the highest power first, as in MATLAB. The coefficients 1, 2, 3 are s squared plus 2 s plus 3. Leading zeros are dropped where it matters: roots ignores them, and residue trims them from both polynomials.

A script writes a polynomial as a plain array of coefficients, highest power first: {1, 2, 3}[1.0, 2.0, 3.0]. Luau and Rune reach roots, polyfit and polyval from this section. Rune also reaches poly, poly_real, charpoly, conv, deconv, polyadd, polyder, polyint and residue. polyval_c is part of the Rust crate and no script calls it.

The three routines both languages reach:

  • roots(c) returns the roots as {re = {...}, im = {...}}#{re: [...], im: [...]}.
  • polyfit(x, y, n) takes the two arrays and the degree n, a whole number from 0 up, and returns the coefficients as an array.
  • polyval(c, x) returns the value at one number x.
Luau
local c = Numerics.polyfit({0, 1, 2}, {1, 3, 5}, 1)
print(c[1], c[2])
print(Numerics.polyval({1, 2, 3}, 2))
local r = Numerics.roots({1, -3, 2})
print(r.re[1], r.re[2])
Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let c = numerics::polyfit([0.0, 1.0, 2.0], [1.0, 3.0, 5.0], 1)?;
    log_info(`${c[0]}, ${c[1]}`);
    let v = numerics::polyval([1.0, 2.0, 3.0], 2.0)?;
    log_info(`${v}`);
    let r = numerics::roots([1.0, -3.0, 2.0])?;
    let re = r["re"];
    log_info(`${re[0]}, ${re[1]}`);
}

The three points lie on the line y = 2x + 1, so the fit is 2 and 1 to within rounding. The polynomial s squared plus 2 s plus 3 at s = 2 is 4 plus 4 plus 3, which is 11. The roots of s squared minus 3 s plus 2 are 1 and 2, so the real parts are those two values in the order the companion matrix gives them, and the imaginary parts are zero.

Building and Rooting

poly takes a list of roots and returns the coefficients of the monic polynomial with those roots; the coefficients are complex in general. poly_real is the real form for roots that are real or come in conjugate pairs: it drops the imaginary parts that rounding leaves behind. charpoly returns the characteristic polynomial of a square matrix, built from its eigenvalues. Rune reaches all three: poly takes the roots as an array or in the re and im form and returns the coefficients in that form, and poly_real and charpoly return a plain array.

roots returns the roots of a polynomial as the eigenvalues of its companion matrix. Trailing zero coefficients become roots at the origin. A polynomial with every coefficient zero has no roots, and the result is empty. A NaN or infinite coefficient raises invalid argument: roots: coefficients must be finite.

A repeated root is only as accurate as the conditioning of the problem allows. A test checks a triple root against that limit.

Evaluating and Fitting

polyval evaluates a real polynomial at a real point by Horner's rule. polyval_c evaluates a real-coefficient polynomial at a complex point.

polyfit fits a polynomial of degree n to points (x, y) by least squares. It builds the Vandermonde matrix from x as given and solves with lstsq, so the rules under Over- and Underdetermined Systems apply. It returns the coefficients only. MATLAB's centering and scaling outputs are not covered, and the fit does not center or scale x. If x and y differ in length it raises dimension mismatch: polyfit: x and y lengths differ, and with fewer than n + 1 points it raises invalid argument: polyfit: need at least n + 1 points.

The figure fits a degree 3 polynomial to 15 points with x from 0 to 3. The coefficients, highest power first, are 0.4765, 0.0936, -2.1015 and 1.0262. The largest residual, a point minus the fit, is about 0.106.

00.511.522.5302468yx15 sample pointsdegree 3 fitresidual (point minus fit)
A degree 3 fit through 15 points, drawn from polyfit_points.csv and polyfit_curve.csv, real output of the library. The coefficients, highest power first, are 0.4765, 0.0936, -2.1015, 1.0262. The curve is the fit evaluated at 151 abscissas and thinned to every third point. The ticks are the point minus the fit at that x, computed from those coefficients.

Multiplying and Dividing

conv returns the coefficients of the product of two polynomials; the result is empty if either input is empty. deconv divides b by a and returns the quotient q and the remainder r, so that b = conv(a, q) + r. A divisor whose leading coefficient is zero raises an invalid-argument error. When b is shorter than a, q is 0 and r is b. polyadd adds two polynomials of different degree by aligning their lowest powers. Rune reaches all three; deconv returns an object with the arrays q and r. Luau does not reach them.This script multiplies s + 2 by s + 3, divides the product by s + 2 again and differentiates it:

Rune
use eustress::log_info;
use eustress::realism::numerics;

pub fn on_init() {
    let p = numerics::conv([1.0, 2.0], [1.0, 3.0])?;
    let d = numerics::deconv(p, [1.0, 2.0])?;
    let q = d["q"];
    let dp = numerics::polyder(p)?;
    log_info(`p = ${p[0]}, ${p[1]}, ${p[2]}`);
    log_info(`q = ${q[0]}, ${q[1]}`);
    log_info(`dp = ${dp[0]}, ${dp[1]}`);
}

The product is s squared plus 5 s plus 6, so the first line prints 1, 5, 6. The quotient is s + 3, so the second line prints 1, 3. The derivative is 2 s + 5, so the third line prints 2, 5. All three are exact apart from rounding.

Derivative and Integral

polyder returns the derivative; the derivative of a constant is the single coefficient 0. polyint returns the antiderivative with an integration constant that you supply. The two are inverses; a test checks that. Rune calls polyder(c) and polyint(c, k) with an array and a number.

Partial Fractions

residue expands b(s) divided by a(s) into partial fractions and returns three lists: the residues r, the poles p, and the direct polynomial term k. The direct term is empty when b has a lower degree than a. A zero denominator raises invalid argument: residue: the denominator is zero. Rune reaches residue(b, a) and returns an object with the fields r and p, each in the re and im form, and k, an array.

Poles that lie close together are treated as one repeated pole, as MATLAB's mpoles does. For a pole of multiplicity m, the residue list holds m entries in a row, the coefficients of 1 over (s - p), 1 over (s - p) squared, and so on in that order, and the pole appears m times in the pole list. A test covers simple poles, complex poles and repeated poles against SciPy.

Only one direction is covered. The inverse, which rebuilds the numerator and denominator from residues, poles and the direct term, is not covered.

07Accuracy and Failure Modes

Singular and Ill-Conditioned Input

No routine on this page prints a warning. A failure is an error, and a result that is numerically poor but finite is returned as an answer. The condition number is how you tell. cond returns the ratio of the largest to the smallest singular value, and it is infinite for a singular matrix.

The tests include an ill-conditioned case: the inverse of a Hilbert matrix. The test checks the inverse against the exact one, and checks that the matrix times its computed inverse is close to the identity.

A worked case: the 12 by 12 Hilbert matrix. Its largest singular value is 1.7954 and its smallest is 1.07e-16. The default rank tolerance, max(rows, columns) times machine epsilon times the largest singular value, is 4.78e-15. Eleven singular values lie above that tolerance and one lies below it, so the rank routine reports 11 for a matrix that has full rank in exact arithmetic. The condition number is 1.68e16. A condition number near the reciprocal of machine epsilon says the matrix is singular to working precision.

12345678910111211e-41e-81e-121e-16singular value (log scale)index (largest first)default rank tolerance 4.784e-15index 12: 1.07e-16, below the tolerance11 values above the tolerance: rank 11 of 12
The 12 singular values of the 12 by 12 Hilbert matrix, drawn from linalg_hilbert_singular_values.csv, real output of the library. The vertical axis is logarithmic and spans 18 decades. The dashed line is max(rows, columns) times machine epsilon times the largest singular value.

Bit-for-Bit Results

With one thread, every routine returns the same bits on every run. The table shows the result of a check on seven kernels, run twice with one thread and twice with 36 threads (every logical processor of an 18-core machine), and then compared across 1, 4 and 36 threads. Each cell says whether the bits are the same. The two middle columns compare two runs at the same thread count. "1 against 4" and "1 against 36" compare the one-thread result with the result at 4 and at 36 threads.

KernelRun to run, 1 threadRun to run, 36 threads1 against 41 against 36
Matrix product, 500 by 500YesYesYesYes
solve, 500 by 500YesYesYesYes
eig, 200 by 200YesYesYesYes
svd, 300 by 300YesYesNoNo
care, 100 statesYesYesYesYes
expm, 200 by 200YesYesYesYes
schur, 200 by 200YesYesYesYes

svd is the one kernel whose bits differ between one thread and several. Its results are identical from run to run at either setting, but the singular values from one thread differ in the last bits from those at 4 threads and at 36 threads. eig, the in-crate solver, gives the same bits across all three thread counts. The svd row compares the singular values. If your script needs the same bits on every machine and every run, keep the default of one thread.

How These Are Checked

The fixtures behind this page are linalg.json (25 cases) and poly.json (11 cases). Together with the other fixture files they hold inputs and expected outputs from NumPy 2.5.5 and SciPy 1.18.1. All 119 tests of the library pass. These tests cover the routines on this page. Further cases check the in-crate paths: kernels.json (19 cases, including the values-only SVD and the consuming solve), svd.json (7, the full SVD) and eig.json (4, hard eigenvalue problems).

RoutineTest
solve (mldivide)solve_square_matches_scipy
solve_ownedsolve_owned_matches_numpy
lstsqlstsq_tall_and_wide_match_numpy
inv, detinv_and_det_match_scipy
invill_conditioned_inverse_is_backward_stable
rank, null, orthrank_null_orth_match_scipy
pinvpinv_matches_scipy_full_rank_and_rank_deficient
normnorms_match_numpy
condcond_matches_numpy_including_hilbert
lulu_reconstructs_with_permutation
qrqr_reconstructs_and_is_orthogonal
cholchol_matches_scipy_and_rejects_indefinite
svdsvd_matches_scipy_and_reconstructs
svd (hard cases)full_svd_matches_scipy_on_hard_cases
svd (divide and conquer, unit test)divide_and_conquer_reconstructs_and_is_orthogonal
svd (divide and conquer, unit test)hard_cases_graded_clustered_rank_deficient
singular_valuessingular_values_match_scipy
eigeig_general_matches_scipy
eig (order 80 hard matrices)eig_hard_matrices_match_scipy_through_the_in_crate_solver
eig (in-crate Schur QR, unit test)schur_and_eigenvectors_on_every_driver_path
eig (in-crate Schur QR, unit test)hard_matrices_on_every_driver_path
eig (in-crate Schur QR, unit test)block_swaps_of_every_shape
eig (in-crate Schur QR, unit test)repeated_eigenvalues_give_finite_vectors
eig_symeig_symmetric_matches_scipy
eigvals on a defective matrixeig_defective_matrix_is_as_accurate_as_scipy
generalized_eigvals (through the zeros of a model)tf2ss_matches_scipy_and_basic_properties
schurschur_is_an_orthogonal_quasi_triangular_factorisation
ordschurordschur_moves_the_stable_eigenvalues_first
schur_complex, rsf2csfcomplex_schur_is_triangular_and_unitary
hesshess_is_orthogonally_similar_and_hessenberg
expmexpm_matches_scipy
expmexpm_of_a_rotation_generator_matches_the_closed_form
logm, sqrtmlogm_and_sqrtm_match_scipy_and_invert
kronkron_matches_numpy
sylvester, lyap, dlyapsylvester_lyap_dlyap_match_scipy
poly, poly_real, charpolypoly_builds_coefficients_from_roots
rootsroots_match_numpy
roots, repeated rootroots_of_a_triple_root_are_within_the_conditioning_limit
polyval, polyfit, conv, deconv, polyaddpolyval_polyfit_conv_deconv_match_numpy
polyder, polyintpolyder_and_polyint_are_inverse
residueresidue_matches_scipy_simple_complex_and_repeated

Tests whose name says matches_scipy or matches_numpy compare against the stored output of that library. The others check a defining property: a factorization multiplies back to A, a Schur vector matrix is orthogonal. The overview page has the full mutation proof; see How It Is Proven. For run-time and accuracy tables, see Performance.

08What's Next

Where to Go from Here

Differential Equations is the next page: it integrates a model through time. Control Design builds on the routines here: gram calls the Lyapunov solvers and c2d calls expm. Numerics has the full MATLAB name table and the list of what is not covered.

Loading Eustress Engine...