Linear systems, Gaussian elimination and LU factorization
Review solving Ax = b with computation in mind: elimination is a product of elementary matrices, recorded as an LU factorization, and pivoting is essential. Derive reduced row echelon form to describe the general solution and explain why an inverse is not calculated to solve a system.
After this lesson you can
- Classify a linear system as having no, one or infinitely many solutions from reduced row echelon form.
- Express Gaussian elimination as a product of elementary matrices and obtain PA = LU.
- Implement LU with partial pivoting and solve systems by forward and backward substitution.
- Estimate factorization and solve costs and justify reusing the factorization for many right-hand sides.
- Explain with a concrete example why pivoting is needed even for a well-conditioned matrix.
Before you start
Motivation: the system underneath everything
Solving is by far the most frequently performed operation in scientific computing. Few serious algorithms put it in the foreground, but nearly all have it in their inner loop:
- Least squares. Fitting a linear model leads to the normal equations : one system per fit.
- Newton’s method. Each iteration of Newton’s method solves , and in a nonlinear system of equations, . A linear system provides the step.
- Kalman filter. Gain of the Kalman filter is calculated not by inverting but by solving a system with it at every time step.
- Simulated physics. An implicit Euler step for stiff system is . If step and do not change, it is the same system with different right-hand sides, thousands of times in succession.
This lesson reviews the algorithm beneath np.linalg.solve with computation in mind. Three ideas structure what follows. Gaussian elimination is a product of elementary matrices, not just a blackboard procedure. Its record is a factorization, , costing operations once and solving each new system in . Pivoting is not optional: without it the algorithm can return nonsense on perfectly healthy matrices. We also see why is never calculated to solve a system, and how to describe infinitely many solutions.
Three possible outcomes
In the first lesson you saw two readings of the system. By rows, each equation is a hyperplane in and solutions are their intersection. By columns, , so solving means finding weights combining columns to reach : a solution exists if and only if lies in the span of the columns. The column reading also gives the solution set’s complete structure.
Proof
If , then , hence . Conversely, . Set is a subspace: either it is , giving a unique solution, or it contains some , in which case all with are distinct solutions.
∎The theorem separates two questions. Existence depends on : a solution exists exactly when lies in the column space of . Uniqueness depends only on : the solution, if it exists, is unique exactly when , meaning columns are linearly independent. For square both occur exactly when is invertible, as in the invertible matrix theorem. If is square and singular, the system never has a unique solution: depending on , it has none or infinitely many.
In with three equations, each equation is a plane and the cases are visible. If the three normals are independent, the planes meet at a point. If coplanar but not all parallel, all three planes are parallel to one direction and two outcomes are possible: they share a line in that direction (a pencil of planes, infinitely many solutions), or have no common point, either intersecting pairwise in three parallel lines (a prism) or having two distinct parallel planes. If all three normals are parallel, so are the planes: if all coincide, solutions form an entire plane; otherwise none exist.
What you should have seen:
- While , exactly one solution exists regardless of . The matrix has : columns are independent, guaranteeing existence and uniqueness.
- At , the third row of is the sum of the first two and is singular. The outcome depends only on : if , the third equation is redundant and a line of solutions remains; otherwise it is contradictory and none remain. Same , opposite outcomes.
- Near singularity, a solution exists but is fragile. It satisfies : with and it already equals , and diverges as . Small data changes move the solution greatly: this is ill-conditioning, measured by the condition number.
Gaussian elimination as a matrix product
Gauss’s idea is to subtract multiples of one equation from the others, eliminating unknowns until reaching a triangular system solved bottom up. For a three-equation example:
The first pivot is . Subtract row 1 multiplied by from row 2, and row 1 multiplied by from row 3:
The second pivot is . With , subtracting times row 2 from row 3 leaves . The system is now upper triangular, with
and back substitution solves it bottom up: , then and . The pivots are and their product, , is : row subtraction does not change the determinant, and a triangular determinant is the product of its diagonal.
Elementary matrices
Each row operation is literally left multiplication by a matrix. This observation turns the algorithm into algebra, from which everything else follows.
Proof
For replacement, . Factor is row of , and places it in row : only row changes, with times row subtracted. For the inverse,
because when . The other two types are immediate: swapping the same rows twice leaves everything unchanged, and scaling by is undone by scaling by .
∎Two consequences. First, because each is invertible, and have exactly the same solutions, justifying the method. Second, multiplication on the right operates on columns. Since , the product subtracts from column column multiplied by (the roles of and reverse), and swaps columns and ; you will use this with complete pivoting.
In the example, the entire elimination is , with
Their product, , is lower triangular with ones on the diagonal, but is not very revealing:
Entry equals , not : in composition, the operation from row 2 to row 3 carries along part of the operation from row 1 to row 2. Remember this; in the LU section you will see that the inverse of has no such problem.
Reduced row echelon form and the general solution
If the matrix is singular or rectangular, a step may have no available pivot in the column: all its entries from the current row down are zero. Elimination does not stop; it moves to the next column without advancing the row, yielding a staircase.
From echelon form, reach reduced form by dividing each row by its pivot and eliminating above pivots too. Doing everything at once, above and below, is Gauss–Jordan elimination. Echelon form is not unique (it depends on chosen operations), but reduced form is; this uniqueness lets us speak of “the” free variables of a system.
Proof
Existence follows from the algorithm. For uniqueness, if with invertible , then : columns of and satisfy exactly the same linear dependence relations. In reduced echelon form those relations are directly readable. Column of is a pivot column if and only if it is not a combination of earlier columns (it has in a row where all earlier columns have ); then it is standard vector , with the number of pivot columns up to it. If it is not a pivot column, its entries are precisely the coefficients expressing it as a combination of preceding pivot columns, which are standard vectors. Thus pivot locations and other entries are determined by dependence relations among columns of , independent of the path. Two reduced echelon forms of agree column by column.
∎The augmented matrix’s reduced form reveals the entire system. If , each nonzero row says “pivot variable combination of free variables number.”
Proof
Row operations preserve the solution set, so study . A row is equation : inconsistent. Without one, each nonzero row solves its pivot variable in terms of free variables, and zero rows say . Free variables can take any value and pivots are determined: exactly , where is the value of the -th free variable, because pivot dependence on free variables is linear. The are independent: at the coordinate of free variable , only has and the others have , so forces . They span : applying the above to the homogeneous system (, ), every is , where is the position of free variable .
∎The number of pivots is the rank of , studied in depth next lesson. With it, every case for system fits in a table:
| Pivots | Shape of | Solutions |
|---|---|---|
| square and invertible | exactly one, for every | |
| tall, independent columns | none or one, depending on | |
| wide, independent rows | infinitely many, for every ( free variables) | |
| rank-deficient | none or infinitely many, depending on |
Return to the planes figure: in the pencil preset, reduced form has two pivots and one gray column, that of , and the solution line is with ; in the prism, the third pivot is in the column of .
LU: elimination stores its multipliers
Suppose elimination needs no swaps. Then with the product of elementary replacement matrices, and . Crucially, , unlike , can be written without calculation.
Proof
Within one step, because cross products contain with . Its inverse is : multiplication produces , and is component of , which is zero. In the product of inverses in order , each cross term has form with , and because is zero in its first positions. Only and terms survive, each in its own column.
∎In reverse order, that of , the cross term is and is not zero: this mixed entries of in the example, where .
In the three-equation example,
with multipliers , and exactly where calculated. In code, and do not even need separate memory: each multiplier is stored in the position it just zeroed, and the resulting matrix contains in the upper triangle and the strict part of below. This is LAPACK’s return format.
There is a second, more structural reading. By the column-by-row rule of matrix multiplication, , where is column of and is row of : a sum of rank-one matrices. Each elimination step subtracts one. After the first, the remaining lower-right block is , the Schur complement of , and the algorithm continues recursively on it. Strang and Moler (2022) develop this view of elimination as successive extraction of rank-one matrices.
Proof
Since is lower triangular and upper triangular, the upper-left block of depends only on blocks of and : , hence . If the factorization exists, , all pivots are nonzero and each . Conversely, suppose the first pivots are nonzero. Restricted to , these steps only subtract multiples of previous rows, preserving determinant: . If , pivot is nonzero too, and induction takes the algorithm to the end. For uniqueness, if , then . The left side is unit lower triangular (proved in the next exercise) and the right upper triangular (the transposed argument applies to invertible upper-triangular matrices). A matrix that is both is diagonal, and its diagonal is that of the left side: identity.
∎Step 1 of 6. Write entry of the product, . Which terms can be nonzero?
The next figure shows all of this in a system , using the Trefethen–Bau matrix.
Solve with LU: two triangular substitutions
With , system splits into two triangular systems: and . Both are solved by substitution, the first top down (forward substitution), the second bottom up (see forward and backward substitution):
When eliminating on augmented matrix , column undergoes the same operations as , and ends up containing : hand elimination performs factorization and forward substitution together. The advantage of separating phases appears with more than one right-hand side; to see it, count.
How much it costs
Measure cost in flops: floating-point additions, subtractions, multiplications or divisions (see flop counting). At step there are rows below the pivot, and each requires a multiplier (one division) and updating active entries (one multiplication and subtraction per entry). Try predicting each step:
In asymptotic notation, factorization is and solving with the factorization is . A reference table of dominant terms:
| Operation | Flops |
|---|---|
| LU factorization | |
| Two triangular substitutions | |
| Cholesky (if is symmetric positive definite) | |
| Gauss–Jordan for one system | |
| Explicit inverse | |
| Product , with the inverse already calculated | |
| Product of two matrices |
The practical consequence is in the ratio: once factorized, each new right-hand side costs versus for factorization, roughly times less. With , solving a new system is a thousand times cheaper than the first. Libraries therefore separate lu_factor from lu_solve, and an implicit simulation step with constant matrix or Newton’s method with frozen Jacobian factors once and reuses it.
Partial pivoting: PA = LU
So far the only obstacle seemed an exactly zero pivot, solved by swapping rows. In floating point that is insufficient. The canonical Trefethen–Bau example has :
The matrix is as harmless as it looks: , and the two lines meet at an angle of about . In exact arithmetic elimination gives and . In double precision, with unit roundoff (see machine epsilon), number is not representable and rounds to : the of disappears. The computed factors are
They exactly factor another matrix, differing from in one entry by . Substitution finishes the job: , and . The first component has error .
The issue is not only the extreme case: accuracy loss is gradual. For any pivot , multiplier amplifies rounding error of when computing , a subtraction of nearly equal numbers followed by division by a small number: relative error is on the order of . A pivot of raises no alarm but loses half the digits.
Backward error and stability
Understand the example by changing the question. Instead of asking how close is to (forward error), ask which nearby system has as its exact solution: the smallest with , measured relative to , is backward error. For linear systems it has a closed formula in terms of the residual:
and the minimum perturbation is with . An algorithm is backward stable if its backward error is always on the order of : it gives the exact solution of a problem differing from the original only by data rounding noise. The two errors are related by problem conditioning, (see forward error bound). With , the example’s disaster can only come from enormous backward error, measured by figure readout : elimination without pivoting is unstable.
The partial-pivoting algorithm
The cure is to choose as pivot at every step the largest absolute entry in the column from the diagonal down, and move its row up. In the example, swapping rows makes the multiplier , , and everything is benign. In general:
- Partial pivoting: at step choose and exchange rows and before elimination.
- Immediate consequence: all multipliers satisfy , so no row is added multiplied by a large number.
With swaps, elimination is , with interleaved permutations. The next theorem moves them all to the right.
Proof
Partial pivoting produces ; if at some step the column is zero from the diagonal downward, take , leaving . Define . Since each is its own inverse, the telescoping product gives . Each with swaps only rows with index greater than , so it fixes and, being symmetric, . Thus is another Gauss transformation with the same multipliers permuted, and the preceding theorem gives with . Finally, with .
∎The proof has an operational reading, visible in the step-by-step figure: when two rows are exchanged, multipliers already stored in those rows are exchanged with them. A useful consequence: , where is the swap count. This is a stable way to compute determinants, as seen in the determinants lesson.
What pivoting guarantees, and what it does not
Wilkinson’s elimination error analysis centers on the growth factor
which measures how entries grow during the process. The central result (Trefethen and Bau, lecture 22) says factors computed with partial pivoting satisfy with . Everything therefore depends on :
- Without pivoting, is unbounded: in the example it equals . There is no guarantee.
- With partial pivoting, implies each step at most doubles entries, so . The bound is attained: the Wilkinson matrix (ones on the diagonal and last column, below the diagonal) causes no swaps and its last column doubles each step. With , and the solution is lost even though ; the lab checks this.
- In practice, such matrices do not arise. For random matrices observed growth is on the order of , and partial-pivoting elimination behaves as a backward-stable algorithm. This is the default in LAPACK, NumPy and PyTorch; detailed analysis belongs to numerical methods (see elimination error analysis).
Some matrices need no pivoting. If is symmetric positive definite, Cholesky factorization is stable without swaps and costs half as much. If is invertible and column-diagonally dominant, , partial pivoting performs no swaps and . Tridiagonal matrices from partial differential equations often fall into one of these cases, which is why the Thomas algorithm, LU without pivoting in , works (see banded systems). At the other extreme, complete pivoting selects the largest element of the entire active submatrix, swapping rows and columns (), with much less growth but comparisons: rarely worthwhile.
Factor once and never invert
Gauss–Jordan and the inverse
If elimination reaches reduced row echelon form on with invertible, the result is . Elementary-matrix algebra explains why: product of all operations satisfies , hence , and the right half, initially , ends as . For example,
Rearranging also yields : every invertible matrix is a product of elementary matrices. This is the algebraic version of “elimination can be undone step by step.”
Why A⁻¹ is not calculated to solve
The fact that can be calculated does not mean it should be. To solve , route loses for three reasons.
- Cost. Forming the inverse costs flops, three times factorization. With many right-hand sides, cost per system equalizes ( in both), but factorization is never worse.
- Accuracy. LU with partial pivoting is backward stable in practice: solves a nearby system exactly and relative residual is on the order of . With the inverse, , and since each column of computed inverse has its own error, that residual can reach the order of . Forward error is on the order of in both, but the inverse is usually worse.
- Structure. Real matrices are often sparse or banded, as are their LU factors to a similar degree. Their inverses are dense. Tridiagonal matrix of the one-dimensional heat equation has bidiagonal factors computed and applied in , whereas every inverse entry is nonzero: . With a million unknowns, factorization takes a few million numbers and the inverse a trillion.
When is computing an inverse legitimate? When you need its entries, rather than its product with a vector. For example, the diagonal of gives linear-regression coefficient variances. Even then calculate through factorization, solving with columns of (or Cholesky if symmetric positive definite). For tiny fixed dimensions, such as inverses in graphics or robotics, closed formulas are reasonable when the matrix is well conditioned.
Implementation from scratch
The first lab implements with partial pivoting and both substitutions. The loop over performs elimination; inside it, active-block updating is one vectorized operation, subtracting a rank-one matrix, and the permutation is stored as an index vector.
import numpy as np
def lu_parcial(A):
"""Factorización PA = LU con pivoteo parcial. Devuelve (P, L, U)."""
U = np.array(A, dtype=float)
n = U.shape[0]
L = np.eye(n)
perm = np.arange(n) # perm[i]: fila original en la posición i
for k in range(n - 1):
# pivote: la mayor |u_ik| con i >= k
r = k + int(np.argmax(np.abs(U[k:, k])))
if r != k:
# se intercambian la parte activa de U, los multiplicadores
# ya guardados en L y la permutación
U[[k, r], k:] = U[[r, k], k:]
L[[k, r], :k] = L[[r, k], :k]
perm[[k, r]] = perm[[r, k]]
if U[k, k] == 0.0: # columna ya nula: A es singular
continue
ell = U[k + 1:, k] / U[k, k] # |ell| <= 1
L[k + 1:, k] = ell
U[k + 1:, k + 1:] -= np.outer(ell, U[k, k + 1:]) # rango 1
U[k + 1:, k] = 0.0
return np.eye(n)[perm], L, U
def sust_adelante(L, b):
"""Resuelve L y = b con L unitriangular inferior."""
y = np.array(b, dtype=float)
for i in range(len(y)):
y[i] -= L[i, :i] @ y[:i]
return y
def sust_atras(U, y):
"""Resuelve U x = y con U triangular superior invertible."""
x = np.array(y, dtype=float)
for i in range(len(x) - 1, -1, -1):
x[i] = (x[i] - U[i, i + 1:] @ x[i + 1:]) / U[i, i]
return x
def resolver(A, b):
P, L, U = lu_parcial(A)
return sust_atras(U, sust_adelante(L, P @ b))
A = np.array([[2., 1, 1, 0], [4, 3, 3, 1], [8, 7, 9, 5], [6, 7, 9, 8]])
P, L, U = lu_parcial(A)
np.set_printoptions(precision=4, suppress=True)
print("P =\n", P, "\nL =\n", L, "\nU =\n", U)
print("PA = LU:", np.allclose(P @ A, L @ U))
print("x =", resolver(A, np.array([3., 8, 24, 25])))These are the factors seen at the end of the step-by-step figure with partial pivoting: multipliers , all with absolute value at most . Now compare with SciPy. Watch its convention: scipy.linalg.lu returns p, l, u with , so our is its .
import scipy.linalg as sla
rng = np.random.default_rng(0)
for n in [5, 50, 300]:
A = rng.standard_normal((n, n))
b = rng.standard_normal(n)
P, L, U = lu_parcial(A)
p, l, u = sla.lu(A) # convención de SciPy: A = p @ l @ u
x = resolver(A, b)
res = np.linalg.norm(P @ A - L @ U) / np.linalg.norm(A)
igual = np.allclose(P, p.T) and np.allclose(L, l) and np.allclose(U, u)
err = np.linalg.norm(x - np.linalg.solve(A, b)) / np.linalg.norm(x)
print(f"n = {n:3d} ‖PA − LU‖/‖A‖ = {res:.1e} igual que SciPy: {igual}"
f" ‖x − solve‖/‖x‖ = {err:.1e}")Factorization residual stays at rounding level (between and a few tens of , growing slowly with ), and factors match LAPACK. Now reproduce the failure without pivoting:
def lu_sin_pivoteo(A):
U = np.array(A, dtype=float)
n = U.shape[0]
L = np.eye(n)
for k in range(n - 1):
ell = U[k + 1:, k] / U[k, k]
L[k + 1:, k] = ell
U[k + 1:, k + 1:] -= np.outer(ell, U[k, k + 1:])
U[k + 1:, k] = 0.0
return L, U
np.set_printoptions(precision=4, suppress=False)
A = np.array([[1e-20, 1.0], [1.0, 1.0]])
b = np.array([1.0, 2.0])
L, U = lu_sin_pivoteo(A)
print("L =\n", L, "\nU =\n", U)
print("L @ U =\n", L @ U, "\n¿L @ U == A?", np.array_equal(L @ U, A))
print("sin pivoteo:", sust_atras(U, sust_adelante(L, b)))
print("con pivoteo:", resolver(A, b), " cond(A) =", round(np.linalg.cond(A), 3))And the gradual dependence on pivot size, with reference :
u = 2.0 ** -53
print(" p error sin pivoteo error con pivoteo u/ε")
for p in range(2, 20, 2):
eps = 10.0 ** -p
A = np.array([[eps, 1.0], [1.0, 1.0]])
x = np.array([1 + eps / (1 - eps), 1 - eps / (1 - eps)])
L, U = lu_sin_pivoteo(A)
x_sin = sust_atras(U, sust_adelante(L, b))
e_sin = np.linalg.norm(x_sin - x) / np.linalg.norm(x)
e_con = np.linalg.norm(resolver(A, b) - x) / np.linalg.norm(x)
print(f"{p:2d} {e_sin:15.1e} {e_con:17.1e} {u / eps:9.1e}")Error without pivoting tracks until it saturates on the order of , while pivoting remains at rounding level. Partial pivoting is not an absolute guarantee, however, as the Wilkinson matrix shows. Also measure growth on random matrices as a lower bound on from :
def wilkinson(n):
W = np.eye(n) - np.tril(np.ones((n, n)), -1)
W[:, -1] = 1.0
return W
rng = np.random.default_rng(1)
print("Matriz de Wilkinson (pivoteo parcial):")
for n in [10, 30, 45, 60]:
W = wilkinson(n)
P, L, U = lu_parcial(W)
x = rng.standard_normal(n)
xh = resolver(W, W @ x)
swaps = not np.array_equal(P, np.eye(n))
err = np.linalg.norm(xh - x) / np.linalg.norm(x)
print(f" n = {n:2d} intercambios: {swaps} max|U| = {np.abs(U).max():8.1e}"
f" κ(W) = {np.linalg.cond(W):5.1f} error relativo = {err:.1e}")
print("Matrices gaussianas aleatorias:")
for n in [50, 100, 200, 400]:
A = rng.standard_normal((n, n))
P, L, U = lu_parcial(A)
rho = np.abs(U).max() / np.abs(A).max()
print(f" n = {n:3d} max|U| / max|A| = {rho:5.2f} √n = {np.sqrt(n):5.1f}")With relative error is on the order of on a matrix with : growth has consumed all 53 mantissa bits. Random matrices, by contrast, grow little and below .
The second lab implements reduced row echelon form and the general solution. Tolerance is the central choice: an entry is treated as zero if it does not exceed , the order of accumulated rounding noise. This is relative tolerance: multiplying the matrix by must not change its rank.
def rref(M, tol=None):
"""Forma escalonada reducida; las entradas con |a| <= tol cuentan como 0."""
R = np.array(M, dtype=float)
m, n = R.shape
if tol is None:
tol = max(m, n) * np.finfo(float).eps * np.abs(R).max()
pivotes = []
fila = 0
for col in range(n):
if fila == m:
break
p = fila + int(np.argmax(np.abs(R[fila:, col])))
if abs(R[p, col]) <= tol: # sin pivote en esta columna
R[fila:, col] = 0.0
continue
R[[fila, p]] = R[[p, fila]]
R[fila] /= R[fila, col] # pivote = 1
otras = [i for i in range(m) if i != fila]
R[otras] -= np.outer(R[otras, col], R[fila]) # ceros arriba y abajo
pivotes.append(col)
fila += 1
return R, pivotes
def solucion_general(A, b, tol=None):
"""(x_p, N): solución particular y base del núcleo (por columnas).
Devuelve (None, None) si el sistema es incompatible."""
A = np.asarray(A, dtype=float)
n = A.shape[1]
R, piv = rref(np.column_stack([A, b]), tol)
if n in piv: # pivote en la columna de b: la fila dice 0 = 1
return None, None
libres = [j for j in range(n) if j not in piv]
xp = np.zeros(n)
N = np.zeros((n, len(libres)))
for fila, col in enumerate(piv):
xp[col] = R[fila, n]
for c, f in enumerate(libres):
N[f, c] = 1.0 # esta variable libre vale 1, las demás 0
for fila, col in enumerate(piv):
N[col, c] = -R[fila, f] + 0.0
return xp, N
np.set_printoptions(precision=4, suppress=True)
A = np.array([[1., 2, 1, 1], [2, 4, 0, 6], [1, 2, 2, -1]])
b = np.array([4., 2, 7])
R, piv = rref(np.column_stack([A, b]))
print("rref([A | b]) =\n", R, "\ncolumnas pivote:", piv)
xp, N = solucion_general(A, b)
print("x_p =", xp, "\nN =\n", N)
t = np.random.default_rng(2).standard_normal(N.shape[1])
print("A (x_p + N t) = b:", np.allclose(A @ (xp + N @ t), b))
print("A N = 0:", np.allclose(A @ N, 0))
print("con b3 = 8:", solucion_general(A, np.array([4., 2, 8])))This is the reduced-form section’s example, with and the two special solutions as columns of . For comparison with exact arithmetic, SymPy computes reduced form over rationals. An innocent-looking matrix shows why tolerance is not optional: with entries , not exactly representable in binary, the matrix has rational rank , but floating-point elimination with zero tolerance finds three pivots. The first cell run can take five to fifteen seconds, mostly downloading and importing SymPy in the browser.
import sympy as sp
Rs, pivs = sp.Matrix(np.column_stack([A, b]).astype(int)).rref()
print("rref exacto (SymPy):", Rs.tolist(), "pivotes", pivs)
D = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]])
Ds = sp.Matrix(3, 3, lambda i, j: sp.Rational(i * 3 + j + 1, 10))
print("rango exacto (SymPy):", Ds.rank())
print("pivotes en coma flotante con tol = 0:", len(rref(D, tol=0.0)[1]))
print("pivotes con la tolerancia por defecto:", len(rref(D)[1]))The professional version
In practice use scipy.linalg.lu_factor and lu_solve, which call LAPACK routines getrf and getrs. Factorization returns in compact form, in the upper triangle and the strict part of below, with the permutation in a format worth understanding: piv[k] says which row was swapped with row k at step k. It is a sequence of swaps, not a permutation.
A = np.array([[2., 1, 1, 0], [4, 3, 3, 1], [8, 7, 9, 5], [6, 7, 9, 8]])
lu, piv = sla.lu_factor(A)
print("lu =\n", lu)
print("piv =", piv)
perm = np.arange(4)
for k, pk in enumerate(piv): # aplicar los intercambios en orden
perm[[k, pk]] = perm[[pk, k]]
print("permutación:", perm)
print("igual que la nuestra:", np.array_equal(np.eye(4)[perm], lu_parcial(A)[0]))
b = np.array([3., 8, 24, 25])
x = sla.lu_solve((lu, piv), b) # A x = b
z = sla.lu_solve((lu, piv), b, trans=1) # Aᵀ z = b, misma factorización
print("x =", x, " z =", z, " Aᵀz = b:", np.allclose(A.T @ z, b))
signo = (-1) ** np.sum(piv != np.arange(4))
print("det A =", signo * np.prod(np.diag(lu)), " np.linalg.det:", np.linalg.det(A))Notice two benefits. With trans=1, the same factorization solves because : two more triangular substitutions, without refactorization (needed by adjoint methods and some optimization steps). The determinant also comes for free from the diagonal and swap count. Now measure reuse in this browser:
import time
rng = np.random.default_rng(3)
n, k = 200, 50
A = rng.standard_normal((n, n))
B = rng.standard_normal((n, k))
t0 = time.perf_counter()
# factoriza k veces
X1 = np.column_stack([np.linalg.solve(A, B[:, j]) for j in range(k)])
t1 = time.perf_counter()
# factoriza una vez y hace k pares de sustituciones
f = sla.lu_factor(A)
X2 = np.column_stack([sla.lu_solve(f, B[:, j]) for j in range(k)])
t2 = time.perf_counter()
# factoriza una vez y sustituye las k columnas en una sola llamada
X3 = sla.lu_solve(sla.lu_factor(A), B)
t3 = time.perf_counter()
print(f"solve {k} veces (factoriza {k} veces): {1e3 * (t1 - t0):7.1f} ms")
print(f"lu_factor + {k} lu_solve: {1e3 * (t2 - t1):7.1f} ms")
print(f"lu_factor + un lu_solve con {k} columnas: {1e3 * (t3 - t2):7.1f} ms")
print("mismo resultado:", np.allclose(X1, X2) and np.allclose(X2, X3))Reusing the factorization is already several times faster, and passing columns in one call multiplies the gain: versus refactoring each time, the difference exceeds an order of magnitude. The second and third lines differ by each call’s fixed overhead (entering SciPy, checking arguments, calling LAPACK), which with calls is paid times and is more significant in Pyodide without optimized BLAS. If all columns are available at once, np.linalg.solve(A, B) with matrix does exactly that: one factorization and block substitution.
Structure matters as much as the algorithm. The heat equation’s tridiagonal matrix needs no pivoting, has bidiagonal factors and a dense inverse:
n = 8
T = 2 * np.eye(n) - np.eye(n, k=1) - np.eye(n, k=-1)
P, L, U = lu_parcial(T)
Tinv = np.linalg.inv(T)
print("intercambios:", not np.array_equal(P, np.eye(n)))
print("no nulos en L:", np.count_nonzero(L), " en U:", np.count_nonzero(U),
" en T⁻¹:", np.count_nonzero(np.abs(Tinv) > 1e-14), "de", n * n)
print("(n + 1) T⁻¹ =\n", np.round((n + 1) * Tinv).astype(int))For banded matrices, scipy.linalg.solve_banded exploits structure without forming the dense matrix, and scipy.sparse.linalg.splu does likewise for general sparse matrices, reordering rows and columns to limit fill-in.
The final idea reuses factorization most economically. Factoring in single precision, much faster on a GPU, gives at most about 7 correct digits and roughly fewer if the matrix is ill-conditioned (in the next cell, with , about 4). But residual , computed in double precision, can correct it by solving with the same cheap factorization: iterative refinement. As long as is not too large for single precision, each iteration gains several digits:
rng = np.random.default_rng(4)
n = 300
Q1, _ = np.linalg.qr(rng.standard_normal((n, n)))
Q2, _ = np.linalg.qr(rng.standard_normal((n, n)))
A = Q1 @ np.diag(np.logspace(0, -4, n)) @ Q2.T # κ(A) = 10⁴
x = rng.standard_normal(n)
b = A @ x
rel = lambda v: np.linalg.norm(v - x) / np.linalg.norm(x)
f32 = sla.lu_factor(A.astype(np.float32)) # LU en precisión simple
xk = sla.lu_solve(f32, b.astype(np.float32)).astype(np.float64)
for it in range(5):
print(f"iteración {it}: error relativo {rel(xk):.1e}")
r = b - A @ xk # residuo en doble precisión
xk = xk + sla.lu_solve(f32, r.astype(np.float32)) # MISMA factorización
print(f"np.linalg.solve en doble: {rel(np.linalg.solve(A, b)):.1e}")In three iterations the solution reaches the accuracy of double-precision factorization, here limited by . On your GPU the speed difference between precisions is real, and PyTorch exposes the same pieces, torch.linalg.lu_factor and torch.linalg.lu_solve, which also batch matrices of shape . The next cell needs the local lab:
import time
import numpy as np
import scipy.linalg as sla
import torch
n = 4000
rng = np.random.default_rng(0)
A = rng.standard_normal((n, n))
x = rng.standard_normal(n)
b = A @ x
gflops = lambda t: 2 * n**3 / 3 / t / 1e9
sla.lu_factor(A[:500, :500]) # calentamiento
t = time.perf_counter()
sla.lu_factor(A)
t_cpu = time.perf_counter() - t
print(f"CPU float64 (LAPACK): {t_cpu:6.3f} s {gflops(t_cpu):7.1f} GFLOP/s")
if torch.cuda.is_available():
for dtype in (torch.float32, torch.float64):
At = torch.tensor(A, dtype=dtype, device="cuda")
torch.linalg.lu_factor(At[:500, :500]) # calentamiento
torch.cuda.synchronize()
t = time.perf_counter()
torch.linalg.lu_factor(At)
torch.cuda.synchronize() # esperar a que acabe la GPU
t_gpu = time.perf_counter() - t
name = str(dtype).replace("torch.", "")
print(f"GPU {name:17s}: {t_gpu:6.3f} s {gflops(t_gpu):7.1f} GFLOP/s")
# precisión mixta: LU en float32 en la GPU; residuos y correcciones en float64
A64 = torch.tensor(A, device="cuda")
b64 = torch.tensor(b, device="cuda")
LU, piv = torch.linalg.lu_factor(A64.float())
xk = torch.linalg.lu_solve(LU, piv, b64.float()[:, None])[:, 0].double()
for it in range(4):
err = np.linalg.norm(xk.cpu().numpy() - x) / np.linalg.norm(x)
print(f"iteración {it}: error relativo {err:.1e}")
r = b64 - A64 @ xk
xk = xk + torch.linalg.lu_solve(LU, piv, r.float()[:, None])[:, 0].double()
x64 = np.linalg.solve(A, b)
print(f"float64 directo: {np.linalg.norm(x64 - x) / np.linalg.norm(x):.1e}")
else:
print("No hay GPU con CUDA disponible.")npm run lab and open the connection link.Consumer GPUs devote much less hardware to double than single precision, so factorization in float32 is faster than in float64. The exact factor depends on size and implementation; check the cell output: on the reference laptop, with , it is about twice as fast. Refinement combines the first’s speed with the second’s accuracy: this is the strategy of mixed-precision LAPACK routines and modern supercomputing benchmarks.
Common mistakes
Exercises
np.linalg.inv(A) @ b worse than np.linalg.solve(A, b)?lu_solve_many(A, B): factor A () once with partial pivoting and solve for all columns of B (), using forward and backward substitution (preferably vectorized across columns). Return X with the shape of B. Do not use np.linalg.solve, np.linalg.inv or SciPy. Tests include matrices requiring pivoting.import numpy as np
def lu_solve_many(A, B):
A = np.array(A, dtype=float)
B = np.array(B, dtype=float)
n = A.shape[0]
# 1. factoriza PA = LU con pivoteo parcial (una sola vez)
# 2. permuta las filas de B
# 3. sustitución hacia delante (L Y = P B) y hacia atrás (U X = Y)
passSummary
- Three outcomes. Solutions form : none, one or infinitely many. Existence is determined by (is it in the column space?); uniqueness only by (independent columns?). A singular square matrix never gives a unique solution, and decides between none and infinitely many.
- Reduced row echelon form. It is unique and reveals everything: pivots, free variables, row of inconsistent systems, and the general solution as a particular solution plus a combination of special solutions. It is an exact tool; floating point requires tolerances.
- LU. Each row operation is an elementary matrix; those at step form a Gauss transformation, and the product of their inverses places each multiplier in position in . With the factorization, solving takes two triangular substitutions.
- Pivoting. A small pivot destroys the solution even for a well-conditioned matrix because it increases growth factor and backward error. Partial pivoting () gives and, barring pathological matrices such as Wilkinson’s, a backward-stable algorithm.
- Do not invert. The inverse costs three times more, can leave residuals times larger and is dense even if is not. Factor once, reuse for each right-hand side and, if speed matters, factor at low precision and refine at high precision.