Module contents
Lesson 4 of 25Review 80 min

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 Ax=b\mat{A}\vb{x} = \vb{b} 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 X⊤X w=X⊤y\mat{X}\T\mat{X}\,\vb{w} = \mat{X}\T\vb{y}: one system d×dd \times d per fit.
  • Newton’s method. Each iteration of Newton’s method solves ∇2f(xt) Δ=−∇f(xt)\hess f(\vb{x}_t)\,\Delta = -\grad f(\vb{x}_t), and in a nonlinear system of nn equations, J(xt) Δ=−F(xt)\mat{J}(\vb{x}_t)\,\Delta = -\vb{F}(\vb{x}_t). A linear system provides the step.
  • Kalman filter. Gain K=PH⊤S−1\mat{K} = \mat{P}\mat{H}\T\mat{S}\inv of the Kalman filter is calculated not by inverting S\mat{S} but by solving a system with it at every time step.
  • Simulated physics. An implicit Euler step for stiff system x˙=Jx\dot{\vb{x}} = \mat{J}\vb{x} is (I−hJ) xt+1=xt(\mat{I} - h\mat{J})\,\vb{x}_{t+1} = \vb{x}_t. If step hh and J\mat{J} 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, PA=LU\mat{P}\mat{A} = \mat{L}\mat{U}, costing 23n3\tfrac{2}{3}n^3 operations once and solving each new system in 2n22n^2. Pivoting is not optional: without it the algorithm can return nonsense on perfectly healthy matrices. We also see why A−1\mat{A}\inv 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 a~i⊤x=bi\tilde{\vb{a}}_i\T\vb{x} = b_i is a hyperplane in Rn\R^n and solutions are their intersection. By columns, Ax=x1a1+⋯+xnan\mat{A}\vb{x} = x_1\vb{a}_1 + \dots + x_n\vb{a}_n, so solving means finding weights combining columns to reach b\vb{b}: a solution exists if and only if b\vb{b} lies in the span of the columns. The column reading also gives the solution set’s complete structure.

Proof

If Ax=b\mat{A}\vb{x} = \vb{b}, then A(x−xp)=b−b=0\mat{A}(\vb{x} - \vb{x}_p) = \vb{b} - \vb{b} = \vb{0}, hence x−xp∈null⁡(A)\vb{x} - \vb{x}_p \in \nullsp(\mat{A}). Conversely, A(xp+z)=b+0=b\mat{A}(\vb{x}_p + \vb{z}) = \vb{b} + \vb{0} = \vb{b}. Set null⁡(A)\nullsp(\mat{A}) is a subspace: either it is {0}\{\vb{0}\}, giving a unique solution, or it contains some z≠0\vb{z} \ne \vb{0}, in which case all xp+tz\vb{x}_p + t\vb{z} with t∈Rt \in \R are distinct solutions.

∎

The theorem separates two questions. Existence depends on b\vb{b}: a solution exists exactly when b\vb{b} lies in the column space of A\mat{A}. Uniqueness depends only on A\mat{A}: the solution, if it exists, is unique exactly when null⁡(A)={0}\nullsp(\mat{A}) = \{\vb{0}\}, meaning columns are linearly independent. For square A\mat{A} both occur exactly when A\mat{A} is invertible, as in the invertible matrix theorem. If A\mat{A} is square and singular, the system never has a unique solution: depending on b\vb{b}, it has none or infinitely many.

In R3\R^3 with three equations, each equation is a plane and the cases are visible. If the three normals a~1,a~2,a~3\tilde{\vb{a}}_1, \tilde{\vb{a}}_2, \tilde{\vb{a}}_3 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.

InteractiveThree planes and their solutions
  • x1+x2+x3=2x_1 + x_2 + x_3 = 2
  • x1−x2=0x_1 - x_2 = 0
  • 2x1−x3=12x_1 - x_3 = 1
  • solution
  • pairwise intersections
[A∣b][\mat{A} \mid \vb{b}] (editable)
rref⁡([A∣b])\operatorname{rref}([\mat{A} \mid \vb{b}])
x1x_1x2x_2x3x_3bb1003/40103/40011/2
Unique solution: x=(34, 34, 12)\vb{x} = (\tfrac{3}{4},\ \tfrac{3}{4},\ \tfrac{1}{2}). Three pivots: no free variables.
−1
1
det⁡A\det\mat{A}4
Pivots of A\mat{A}3
Pivots of [A∣b][\mat{A} \mid \vb{b}]3
Free variablesnone
Each equation of Ax=b\mat{A}\vb{x} = \vb{b} is a plane in R3\R^3, and solutions are points common to all three. Move a33a_{33} toward 11 with b3=1b_3 = 1: the intersection point moves away and disappears at a33=1a_{33} = 1. Repeat with b3=2b_3 = 2: the point stays fixed and becomes a whole line at a33=1a_{33} = 1. When normals are coplanar, “Look along the common direction” shows the prism as a triangle and the pencil as three concurrent lines. Below, the reduced row echelon form of [A∣b][\mat{A} \mid \vb{b}], built later, marks pivots (boxes), free variables (gray column) and the contradictory row 0=10 = 1 (red).

What you should have seen:

  • While a33≠1a_{33} \ne 1, exactly one solution exists regardless of b3b_3. The matrix has det⁡A=2(1−a33)≠0\det\mat{A} = 2(1 - a_{33}) \ne 0: columns are independent, guaranteeing existence and uniqueness.
  • At a33=1a_{33} = 1, the third row of A\mat{A} is the sum of the first two and A\mat{A} is singular. The outcome depends only on b3b_3: if b3=b1+b2=2b_3 = b_1 + b_2 = 2, the third equation is redundant and a line of solutions remains; otherwise it is contradictory and none remain. Same A\mat{A}, opposite outcomes.
  • Near singularity, a solution exists but is fragile. It satisfies x1=x2=(b3−2a33)/(2−2a33)x_1 = x_2 = (b_3 - 2a_{33})/(2 - 2a_{33}): with b3=1b_3 = 1 and a33=0.9a_{33} = 0.9 it already equals −4-4, and diverges as a33→1a_{33} \to 1. 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:

2x1+x2+x3=54x1−6x2+x3=−2−2x1+7x2+2x3=9\begin{aligned} 2x_1 + x_2 + x_3 &= 5 \\ 4x_1 - 6x_2 \phantom{{}+x_3} &= -2 \\ -2x_1 + 7x_2 + 2x_3 &= 9 \end{aligned}

The first pivot is a11=2a_{11} = 2. Subtract row 1 multiplied by ℓ21=4/2=2\ell_{21} = 4/2 = 2 from row 2, and row 1 multiplied by ℓ31=−2/2=−1\ell_{31} = -2/2 = -1 from row 3:

2x1+x2+x3=5−8x2−2x3=−128x2+3x3=14\begin{aligned} 2x_1 + x_2 + x_3 &= 5 \\ -8x_2 - 2x_3 &= -12 \\ 8x_2 + 3x_3 &= 14 \end{aligned}

The second pivot is −8-8. With ℓ32=8/(−8)=−1\ell_{32} = 8/(-8) = -1, subtracting ℓ32\ell_{32} times row 2 from row 3 leaves x3=2x_3 = 2. The system is now upper triangular, Ux=c\mat{U}\vb{x} = \vb{c} with

U=[2110−8−2001],c=[5−122],\mat{U} = \begin{bmatrix} 2 & 1 & 1 \\ 0 & -8 & -2 \\ 0 & 0 & 1 \end{bmatrix}, \qquad \vb{c} = \begin{bmatrix} 5 \\ -12 \\ 2 \end{bmatrix},

and back substitution solves it bottom up: x3=2x_3 = 2, then x2=(−12+2⋅2)/(−8)=1x_2 = (-12 + 2\cdot 2)/(-8) = 1 and x1=(5−1−2)/2=1x_1 = (5 - 1 - 2)/2 = 1. The pivots are 2,−8,12, -8, 1 and their product, −16-16, is det⁡A\det\mat{A}: 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, Eik(ℓ) A=A−ℓ ei(ek⊤A)\mat{E}_{ik}(\ell)\,\mat{A} = \mat{A} - \ell\,\vb{e}_i(\vb{e}_k\T\mat{A}). Factor ek⊤A\vb{e}_k\T\mat{A} is row kk of A\mat{A}, and ei\vb{e}_i places it in row ii: only row ii changes, with ℓ\ell times row kk subtracted. For the inverse,

(I−ℓ eiek⊤)(I+ℓ eiek⊤)=I−ℓ2 ei(ek⊤ei)ek⊤=I,(\mat{I} - \ell\,\vb{e}_i\vb{e}_k\T)(\mat{I} + \ell\,\vb{e}_i\vb{e}_k\T) = \mat{I} - \ell^2\,\vb{e}_i(\vb{e}_k\T\vb{e}_i)\vb{e}_k\T = \mat{I},

because ek⊤ei=0\vb{e}_k\T\vb{e}_i = 0 when i≠ki \ne k. The other two types are immediate: swapping the same rows twice leaves everything unchanged, and scaling by cc is undone by scaling by 1/c1/c.

∎

Two consequences. First, because each E\mat{E} is invertible, Ax=b\mat{A}\vb{x} = \vb{b} and EAx=Eb\mat{E}\mat{A}\vb{x} = \mat{E}\vb{b} have exactly the same solutions, justifying the method. Second, multiplication on the right operates on columns. Since A Eik(ℓ)=A−ℓ (Aei)ek⊤\mat{A}\,\mat{E}_{ik}(\ell) = \mat{A} - \ell\,(\mat{A}\vb{e}_i)\vb{e}_k\T, the product subtracts from column kk column ii multiplied by ℓ\ell (the roles of ii and kk reverse), and APik\mat{A}\mat{P}_{ik} swaps columns ii and kk; you will use this with complete pivoting.

In the example, the entire elimination is E32E31E21A=U\mat{E}_{32}\mat{E}_{31}\mat{E}_{21}\mat{A} = \mat{U}, with

E21=[100−210001],E31=[100010101],E32=[100010011].\mat{E}_{21} = \begin{bmatrix} 1 & 0 & 0 \\ -2 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}, \quad \mat{E}_{31} = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 1 & 0 & 1 \end{bmatrix}, \quad \mat{E}_{32} = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 1 \end{bmatrix}.

Their product, M=E32E31E21\mat{M} = \mat{E}_{32}\mat{E}_{31}\mat{E}_{21}, is lower triangular with ones on the diagonal, but is not very revealing:

M=[100−210−111].\mat{M} = \begin{bmatrix} 1 & 0 & 0 \\ -2 & 1 & 0 \\ -1 & 1 & 1 \end{bmatrix}.

Entry (3,1)(3, 1) equals −1-1, not −ℓ31=1-\ell_{31} = 1: 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 M\mat{M} 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 R=EA\mat{R} = \mat{E}\mat{A} with invertible E\mat{E}, then Ax=0  ⟺  Rx=0\mat{A}\vb{x} = \vb{0} \iff \mat{R}\vb{x} = \vb{0}: columns of A\mat{A} and R\mat{R} satisfy exactly the same linear dependence relations. In reduced echelon form those relations are directly readable. Column jj of R\mat{R} is a pivot column if and only if it is not a combination of earlier columns (it has 11 in a row where all earlier columns have 00); then it is standard vector et\vb{e}_t, with tt 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 A\mat{A}, independent of the path. Two reduced echelon forms of A\mat{A} agree column by column.

∎

The augmented matrix’s reduced form reveals the entire system. If [R∣d]=rref⁡([A∣b])[\mat{R} \mid \vb{d}] = \operatorname{rref}([\mat{A} \mid \vb{b}]), each nonzero row says “pivot variable ++ combination of free variables == number.”

Proof

Row operations preserve the solution set, so study Rx=d\mat{R}\vb{x} = \vb{d}. A row [ 0⋯0∣1 ][\,0 \cdots 0 \mid 1\,] is equation 0=10 = 1: inconsistent. Without one, each nonzero row solves its pivot variable in terms of free variables, and zero rows say 0=00 = 0. Free variables can take any value and pivots are determined: exactly xp+∑jtjsj\vb{x}_p + \sum_j t_j\vb{s}_j, where tjt_j is the value of the jj-th free variable, because pivot dependence on free variables is linear. The sj\vb{s}_j are independent: at the coordinate of free variable jj, only sj\vb{s}_j has 11 and the others have 00, so ∑jtjsj=0\sum_j t_j\vb{s}_j = \vb{0} forces tj=0t_j = 0. They span null⁡(A)\nullsp(\mat{A}): applying the above to the homogeneous system (d=0\vb{d} = \vb{0}, xp=0\vb{x}_p = \vb{0}), every z∈null⁡(A)\vb{z} \in \nullsp(\mat{A}) is ∑jzfjsj\sum_j z_{f_j}\vb{s}_j, where fjf_j is the position of free variable jj.

∎

The number of pivots rr is the rank of A\mat{A}, studied in depth next lesson. With it, every case for system m×nm \times n fits in a table:

PivotsShape of A\mat{A}Solutions
r=m=nr = m = nsquare and invertibleexactly one, for every b\vb{b}
r=n<mr = n < mtall, independent columnsnone or one, depending on b\vb{b}
r=m<nr = m < nwide, independent rowsinfinitely many, for every b\vb{b} (n−rn - r free variables)
r<min⁡(m,n)r < \min(m, n)rank-deficientnone or infinitely many, depending on b\vb{b}

Return to the planes figure: in the pencil preset, reduced form has two pivots and one gray column, that of x3x_3, and the solution line is xp+t s\vb{x}_p + t\,\vb{s} with s=(−12,−12,1)\vb{s} = (-\tfrac12, -\tfrac12, 1); in the prism, the third pivot is in the column of b\vb{b}.

LU: elimination stores its multipliers

Suppose elimination needs no swaps. Then MA=U\mat{M}\mat{A} = \mat{U} with M\mat{M} the product of elementary replacement matrices, and A=M−1U\mat{A} = \mat{M}\inv\mat{U}. Crucially, M−1\mat{M}\inv, unlike M\mat{M}, can be written without calculation.

Proof

Within one step, Enk⋯Ek+1,k=I−ℓkek⊤\mat{E}_{nk}\cdots\mat{E}_{k+1,k} = \mat{I} - \boldsymbol{\ell}_k\vb{e}_k\T because cross products contain ek⊤ei=0\vb{e}_k\T\vb{e}_i = 0 with i>ki > k. Its inverse is I+ℓkek⊤\mat{I} + \boldsymbol{\ell}_k\vb{e}_k\T: multiplication produces ℓk(ek⊤ℓk)ek⊤\boldsymbol{\ell}_k(\vb{e}_k\T\boldsymbol{\ell}_k)\vb{e}_k\T, and ek⊤ℓk\vb{e}_k\T\boldsymbol{\ell}_k is component kk of ℓk\boldsymbol{\ell}_k, which is zero. In the product of inverses in order L1−1L2−1⋯\mat{L}_1\inv\mat{L}_2\inv\cdots, each cross term has form ℓj(ej⊤ℓk)ek⊤\boldsymbol{\ell}_j(\vb{e}_j\T\boldsymbol{\ell}_k)\vb{e}_k\T with j<kj < k, and ej⊤ℓk=0\vb{e}_j\T\boldsymbol{\ell}_k = 0 because ℓk\boldsymbol{\ell}_k is zero in its first kk positions. Only I\mat{I} and terms ℓkek⊤\boldsymbol{\ell}_k\vb{e}_k\T survive, each in its own column.

∎

In reverse order, that of M=L2L1\mat{M} = \mat{L}_2\mat{L}_1, the cross term is ℓ2(e2⊤ℓ1)e1⊤\boldsymbol{\ell}_2(\vb{e}_2\T\boldsymbol{\ell}_1)\vb{e}_1\T and e2⊤ℓ1=ℓ21\vb{e}_2\T\boldsymbol{\ell}_1 = \ell_{21} is not zero: this mixed entries of M\mat{M} in the example, where M31=−ℓ31+ℓ32ℓ21=1−2=−1M_{31} = -\ell_{31} + \ell_{32}\ell_{21} = 1 - 2 = -1.

In the three-equation example,

[2114−60−272]⏟A=[100210−1−11]⏟L[2110−8−2001]⏟U,\underbrace{\begin{bmatrix} 2 & 1 & 1 \\ 4 & -6 & 0 \\ -2 & 7 & 2 \end{bmatrix}}_{\mat{A}} = \underbrace{\begin{bmatrix} 1 & 0 & 0 \\ 2 & 1 & 0 \\ -1 & -1 & 1 \end{bmatrix}}_{\mat{L}} \underbrace{\begin{bmatrix} 2 & 1 & 1 \\ 0 & -8 & -2 \\ 0 & 0 & 1 \end{bmatrix}}_{\mat{U}},

with multipliers ℓ21=2\ell_{21} = 2, ℓ31=−1\ell_{31} = -1 and ℓ32=−1\ell_{32} = -1 exactly where calculated. In code, L\mat{L} and U\mat{U} do not even need separate memory: each multiplier is stored in the position it just zeroed, and the resulting matrix contains U\mat{U} in the upper triangle and the strict part of L\mat{L} below. This is LAPACK’s return format.

There is a second, more structural reading. By the column-by-row rule of matrix multiplication, A=LU=∑klkuk⊤\mat{A} = \mat{L}\mat{U} = \sum_k \vb{l}_k\vb{u}_k\T, where lk\vb{l}_k is column kk of L\mat{L} and uk⊤\vb{u}_k\T is row kk of U\mat{U}: a sum of rank-one matrices. Each elimination step subtracts one. After the first, the remaining lower-right block is A22−a21a12⊤/a11\mat{A}_{22} - \vb{a}_{21}\vb{a}_{12}\T/a_{11}, the Schur complement of a11a_{11}, 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 L\mat{L} is lower triangular and U\mat{U} upper triangular, the upper-left k×kk \times k block of LU\mat{L}\mat{U} depends only on blocks k×kk \times k of L\mat{L} and U\mat{U}: A[k]=L[k]U[k]\mat{A}_{[k]} = \mat{L}_{[k]}\mat{U}_{[k]}, hence det⁡A[k]=u11⋯ukk\det\mat{A}_{[k]} = u_{11}\cdots u_{kk}. If the factorization exists, det⁡A=u11⋯unn≠0\det\mat{A} = u_{11}\cdots u_{nn} \ne 0, all pivots are nonzero and each det⁡A[k]≠0\det\mat{A}_{[k]} \ne 0. Conversely, suppose the first k−1k - 1 pivots are nonzero. Restricted to A[k]\mat{A}_{[k]}, these steps only subtract multiples of previous rows, preserving determinant: det⁡A[k]=u11⋯uk−1,k−1 akk(k)\det\mat{A}_{[k]} = u_{11}\cdots u_{k-1,k-1}\,a^{(k)}_{kk}. If det⁡A[k]≠0\det\mat{A}_{[k]} \ne 0, pivot kk is nonzero too, and induction takes the algorithm to the end. For uniqueness, if LU=L′U′\mat{L}\mat{U} = \mat{L}'\mat{U}', then L′−1L=U′U−1\mat{L}'^{-1}\mat{L} = \mat{U}'\mat{U}\inv. 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.

∎
ProofUnit lower-triangular matrices form a group
Prove: If S,T∈Rn×n\mat{S}, \mat{T} \in \R^{n\times n} are lower triangular with diagonal ones, so is ST\mat{S}\mat{T}; moreover S\mat{S} is invertible and S−1\mat{S}\inv is lower triangular with diagonal ones.
0
A matrix T\mat{T} is lower triangular if tij=0t_{ij} = 0 whenever i<ji < j.

Step 1 of 6. Write entry (i,j)(i, j) of the product, ∑ksiktkj\sum_k s_{ik}t_{kj}. Which terms can be nonzero?

The next figure shows all of this in a system 4×44 \times 4, using the Trefethen–Bau matrix.

InteractiveElimination step by step with its elementary matrix
step 0 of 7
Augmented matrix [A∣b][\mat{A} \mid \vb{b}]. Each step left-multiplies by an elementary matrix E\mat{E} and stores its multiplier in L\mat{L}. Press ▶ or advance step by step.
E\mat{E}
1000010000100001
no step yet
[A(0)∣b(0)][\mat{A}^{(0)} \mid \vb{b}^{(0)}]
2110343318879524679825
the initial augmented matrix
L\mat{L}
1000010000100001
stored multipliers
P\mat{P}
1000010000100001
without pivoting, always I\mat{I}
  • pivot
  • row being changed
  • multiplier ℓik\ell_{ik}
  • swap
Without pivoting, the multipliers are integers and U\mat{U} has pivots 2,1,2,22, 1, 2, 2. Partial pivoting changes the rows, the multipliers satisfy ∣ℓik∣≤1\abs{\ell_{ik}} \le 1, and the factorization is different: PA=LU\mat{P}\mat{A} = \mat{L}\mat{U}.
Strategy
Step0 of 7
Growth ρ\rho11
Invariant ∥PA−LA(s)∥/∥A∥\lVert \mat{P}\mat{A} - \mat{L}\mat{A}^{(s)} \rVert / \lVert \mat{A} \rVert00
Relative error of x^\hat{\vb{x}}at the end
Each frame is an elementary operation. Left: matrix E\mat{E} or P\mat{P} performing it; center: the augmented matrix after application; right: L\mat{L} with stored multipliers and accumulated permutation P\mat{P}. Step through and check each multiplier appears with a minus in Eik\mat{E}_{ik} and a plus in the same position in L\mat{L}. The “invariant” readout measures PA−LA(s)\mat{P}\mat{A} - \mat{L}\mat{A}^{(s)}: it is zero at every step in exact arithmetic. Then try “Zero pivot at step 2” and “Tiny pivot,” with and without pivoting.

Solve with LU: two triangular substitutions

With A=LU\mat{A} = \mat{L}\mat{U}, system Ax=b\mat{A}\vb{x} = \vb{b} splits into two triangular systems: Ly=b\mat{L}\vb{y} = \vb{b} and Ux=y\mat{U}\vb{x} = \vb{y}. Both are solved by substitution, the first top down (forward substitution), the second bottom up (see forward and backward substitution):

yi=bi−∑j<iℓij yj,i=1,…,n,xi=1uii(yi−∑j>iuij xj),i=n,…,1.\begin{aligned} y_i &= b_i - \sum_{j<i}\ell_{ij}\,y_j, & i &= 1, \dots, n, \\ x_i &= \frac{1}{u_{ii}}\Big(y_i - \sum_{j>i}u_{ij}\,x_j\Big), & i &= n, \dots, 1. \end{aligned}

When eliminating on augmented matrix [A∣b][\mat{A} \mid \vb{b}], column b\vb{b} undergoes the same operations as L−1\mat{L}\inv, and ends up containing y\vb{y}: 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 kk there are n−kn - k rows below the pivot, and each requires a multiplier (one division) and updating n−kn - k active entries (one multiplication and subtraction per entry). Try predicting each step:

step k:(n−k) (2(n−k)+1) flops\text{step } k: \quad (n - k)\,\big(2(n - k) + 1\big) \text{ flops}
n−kn - k rows, each with one division and n−kn - k multiplication–subtraction pairs.
1/5

In asymptotic notation, factorization is Θ(n3)\Theta(n^3) and solving with the factorization is Θ(n2)\Theta(n^2). A reference table of dominant terms:

OperationFlops
LU factorization23n3\tfrac{2}{3}n^3
Two triangular substitutions2n22n^2
Cholesky (if A\mat{A} is symmetric positive definite)13n3\tfrac{1}{3}n^3
Gauss–Jordan for one systemn3n^3
Explicit inverse A−1\mat{A}\inv2n32n^3
Product A−1b\mat{A}\inv\vb{b}, with the inverse already calculated2n22n^2
Product of two matrices n×nn \times n2n32n^3

The practical consequence is in the ratio: once factorized, each new right-hand side costs 2n22n^2 versus 23n3\tfrac{2}{3}n^3 for factorization, roughly n/3n/3 times less. With n=3000n = 3000, 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 ε=10−20\eps = 10^{-20}:

A=[ε111],b=[12],x=[1/(1−ε)(1−2ε)/(1−ε)]≈[11].\mat{A} = \begin{bmatrix} \eps & 1 \\ 1 & 1 \end{bmatrix}, \qquad \vb{b} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}, \qquad \vb{x} = \begin{bmatrix} 1/(1 - \eps) \\ (1 - 2\eps)/(1 - \eps) \end{bmatrix} \approx \begin{bmatrix} 1 \\ 1 \end{bmatrix}.

The matrix is as harmless as it looks: κ2(A)≈2.62\kappa_2(\mat{A}) \approx 2.62, and the two lines meet at an angle of about 45°45°. In exact arithmetic elimination gives ℓ21=1020\ell_{21} = 10^{20} and u22=1−1020u_{22} = 1 - 10^{20}. In double precision, with unit roundoff u=2−53≈1.1×10−16u = 2^{-53} \approx 1.1 \times 10^{-16} (see machine epsilon), number 1−10201 - 10^{20} is not representable and rounds to −1020-10^{20}: the 11 of a22a_{22} disappears. The computed factors are

L^=[1010201],U^=[10−2010−1020],L^U^=[10−20110]≠A.\hat{\mat{L}} = \begin{bmatrix} 1 & 0 \\ 10^{20} & 1 \end{bmatrix}, \quad \hat{\mat{U}} = \begin{bmatrix} 10^{-20} & 1 \\ 0 & -10^{20} \end{bmatrix}, \quad \hat{\mat{L}}\hat{\mat{U}} = \begin{bmatrix} 10^{-20} & 1 \\ 1 & 0 \end{bmatrix} \ne \mat{A}.

They exactly factor another matrix, differing from A\mat{A} in one entry by 11. Substitution finishes the job: y2=fl⁡(2−1020)=−1020y_2 = \operatorname{fl}(2 - 10^{20}) = -10^{20}, x^2=1\hat{x}_2 = 1 and x^1=(1−x^2)/ε=0\hat{x}_1 = (1 - \hat{x}_2)/\eps = 0. The first component has error 100 %100\,\%.

The issue is not only the extreme case: accuracy loss is gradual. For any pivot ε\eps, multiplier 1/ε1/\eps amplifies rounding error of x^2\hat{x}_2 when computing x^1=(1−x^2)/ε\hat{x}_1 = (1 - \hat{x}_2)/\eps, a subtraction of nearly equal numbers followed by division by a small number: relative error is on the order of u/εu/\eps. A pivot of 10−810^{-8} raises no alarm but loses half the digits.

InteractiveThe tiny pivot, operation by operation
  • εx1+x2=1\eps x_1 + x_2 = 1
  • x1+x2=2x_1 + x_2 = 2
  • equation 2 actually solved
  • exact x\vb{x}
  • computed x^\hat{\vb{x}}
operationin double precisionrelative error1ℓ21=1/ε\ell_{21} = 1/\eps1.00000×10162×10−172u22=1−ℓ21u_{22} = 1 - \ell_{21}−1.00000×10161×10−163y2=2−ℓ21y_2 = 2 - \ell_{21}−1.00000×101604x2=y2/u22x_2 = y_2 / u_{22}11×10−165x1=(1−x2)/εx_1 = (1 - x_2)/\eps2.220451
Operations 1 through 4 are accurate up to roundoff. Trouble arrives at step 5: 1−x21 - x_2 subtracts nearly equal numbers, leaving the error in x2x_2, amplified by 1/ε1/\eps when divided by ε\eps.
Relative error of x^\hat{\vb{x}} against pp (zero errors plotted at 10−1710^{-17})
  • with pivoting
  • without pivoting
  • reference u/ε
Strategy
p = 16
κ2(A)\kappa_2(\mat{A}) (condition number)2.62
Growth ρ\rho1.0×10161.0 \times 10^{16}
x^\hat{\vb{x}}(2.2204, 1)
Backward error η\eta3×10−13 \times 10^{-1}
Relative error of x^\hat{\vb{x}}9×10−19 \times 10^{-1}
System εx1+x2=1\eps x_1 + x_2 = 1, x1+x2=2x_1 + x_2 = 2 solved in real double precision with ε=10−p\eps = 10^{-p}. The table measures error in each elimination operation. Without pivoting, increase pp gradually and watch the curve: error in x^\hat{\vb{x}} follows u/εu/\eps, so each order of magnitude of pivot costs one digit, and at p=16p = 16 the computed solution no longer satisfies the second equation. The dashed line is the equation the algorithm actually solved. Switch to “With pivoting”: the multiplier becomes ε\eps and every operation retains precision. The lines always meet at a healthy angle, so the algorithm is responsible, not the problem.

Backward error and stability

Understand the example by changing the question. Instead of asking how close x^\hat{\vb{x}} is to x\vb{x} (forward error), ask which nearby system has x^\hat{\vb{x}} as its exact solution: the smallest δA\delta\mat{A} with (A+δA)x^=b(\mat{A} + \delta\mat{A})\hat{\vb{x}} = \vb{b}, measured relative to A\mat{A}, is backward error. For linear systems it has a closed formula in terms of the residual:

η(x^)=min⁡{∥δA∥2∥A∥2:(A+δA)x^=b}=∥b−Ax^∥2∥A∥2∥x^∥2,\eta(\hat{\vb{x}}) = \min\Big\{\frac{\norm{\delta\mat{A}}_2}{\norm{\mat{A}}_2} : (\mat{A} + \delta\mat{A})\hat{\vb{x}} = \vb{b}\Big\} = \frac{\norm{\vb{b} - \mat{A}\hat{\vb{x}}}_2}{\norm{\mat{A}}_2\norm{\hat{\vb{x}}}_2},

and the minimum perturbation is δA=rx^⊤/∥x^∥22\delta\mat{A} = \vb{r}\hat{\vb{x}}\T/\norm{\hat{\vb{x}}}_2^2 with r=b−Ax^\vb{r} = \vb{b} - \mat{A}\hat{\vb{x}}. An algorithm is backward stable if its backward error is always on the order of uu: 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, error hacia delante≲κ(A)⋅error hacia atraˊs\text{error hacia delante} \lesssim \kappa(\mat{A}) \cdot \text{error hacia atrás} (see forward error bound). With κ(A)≈2.6\kappa(\mat{A}) \approx 2.6, the example’s disaster can only come from enormous backward error, measured by figure readout η\eta: 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 ε\eps, u22=1−εu_{22} = 1 - \eps, and everything is benign. In general:

  • Partial pivoting: at step kk choose r=arg max⁡i≥k∣aik(k)∣r = \argmax_{i \ge k}\abs{a^{(k)}_{ik}} and exchange rows kk and rr before elimination.
  • Immediate consequence: all multipliers satisfy ∣ℓik∣≤1\abs{\ell_{ik}} \le 1, so no row is added multiplied by a large number.

With swaps, elimination is Ln−1Pn−1⋯L2P2L1P1A=U\mat{L}_{n-1}\mat{P}_{n-1}\cdots\mat{L}_2\mat{P}_2\mat{L}_1\mat{P}_1\mat{A} = \mat{U}, with interleaved permutations. The next theorem moves them all to the right.

Proof

Partial pivoting produces Ln−1Pn−1⋯L1P1A=U\mat{L}_{n-1}\mat{P}_{n-1}\cdots\mat{L}_1\mat{P}_1\mat{A} = \mat{U}; if at some step the column is zero from the diagonal downward, take Lk=I\mat{L}_k = \mat{I}, leaving ukk=0u_{kk} = 0. Define Lk′=Pn−1⋯Pk+1 Lk Pk+1⋯Pn−1\mat{L}'_k = \mat{P}_{n-1}\cdots\mat{P}_{k+1}\,\mat{L}_k\,\mat{P}_{k+1}\cdots\mat{P}_{n-1}. Since each Pj\mat{P}_j is its own inverse, the telescoping product gives Ln−1′⋯L1′(Pn−1⋯P1)A=U\mat{L}'_{n-1}\cdots\mat{L}'_1(\mat{P}_{n-1}\cdots\mat{P}_1)\mat{A} = \mat{U}. Each Pj\mat{P}_j with j>kj > k swaps only rows with index greater than kk, so it fixes ek\vb{e}_k and, being symmetric, Pj(I−ℓkek⊤)Pj=I−(Pjℓk)ek⊤\mat{P}_j(\mat{I} - \boldsymbol{\ell}_k\vb{e}_k\T)\mat{P}_j = \mat{I} - (\mat{P}_j\boldsymbol{\ell}_k)\vb{e}_k\T. Thus Lk′\mat{L}'_k is another Gauss transformation with the same multipliers permuted, and the preceding theorem gives PA=LU\mat{P}\mat{A} = \mat{L}\mat{U} with P=Pn−1⋯P1\mat{P} = \mat{P}_{n-1}\cdots\mat{P}_1. Finally, det⁡(P)det⁡(A)=u11⋯unn\det(\mat{P})\det(\mat{A}) = u_{11}\cdots u_{nn} with det⁡P=±1\det\mat{P} = \pm 1.

∎

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: det⁡A=(−1)s u11⋯unn\det\mat{A} = (-1)^s\,u_{11}\cdots u_{nn}, where ss 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

ρ=max⁡i,j,k∣aij(k)∣max⁡i,j∣aij∣,\rho = \frac{\max_{i,j,k}\abs{a^{(k)}_{ij}}}{\max_{i,j}\abs{a_{ij}}},

which measures how entries grow during the process. The central result (Trefethen and Bau, lecture 22) says factors computed with partial pivoting satisfy L^U^=P^A+δA\hat{\mat{L}}\hat{\mat{U}} = \hat{\mat{P}}\mat{A} + \delta\mat{A} with ∥δA∥/∥A∥=O(ρ u)\norm{\delta\mat{A}}/\norm{\mat{A}} = \bigO(\rho\,u). Everything therefore depends on ρ\rho:

  • Without pivoting, ρ\rho is unbounded: in the example it equals 1/ε1/\eps. There is no guarantee.
  • With partial pivoting, ∣ℓik∣≤1\abs{\ell_{ik}} \le 1 implies each step at most doubles entries, so ρ≤2n−1\rho \le 2^{n-1}. The bound is attained: the Wilkinson matrix (ones on the diagonal and last column, −1-1 below the diagonal) causes no swaps and its last column doubles each step. With n=60n = 60, ρ=259≈6×1017\rho = 2^{59} \approx 6 \times 10^{17} and the solution is lost even though κ(W)≈27\kappa(\mat{W}) \approx 27; the lab checks this.
  • In practice, such matrices do not arise. For random matrices observed growth is on the order of n\sqrt{n}, 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 A\mat{A} is symmetric positive definite, Cholesky factorization is stable without swaps and costs half as much. If A\mat{A} is invertible and column-diagonally dominant, ∣ajj∣≥∑i≠j∣aij∣\abs{a_{jj}} \ge \sum_{i \ne j}\abs{a_{ij}}, partial pivoting performs no swaps and ρ≤2\rho \le 2. Tridiagonal matrices from partial differential equations often fall into one of these cases, which is why the Thomas algorithm, LU without pivoting in O(n)\bigO(n), works (see banded systems). At the other extreme, complete pivoting selects the largest element of the entire active submatrix, swapping rows and columns (PAQ=LU\mat{P}\mat{A}\mat{Q} = \mat{L}\mat{U}), with much less growth but O(n3)\bigO(n^3) comparisons: rarely worthwhile.

Factor once and never invert

Gauss–Jordan and the inverse

If elimination reaches reduced row echelon form on [A∣I][\mat{A} \mid \mat{I}] with A\mat{A} invertible, the result is [I∣A−1][\mat{I} \mid \mat{A}\inv]. Elementary-matrix algebra explains why: product E=EN⋯E1\mat{E} = \mat{E}_N\cdots\mat{E}_1 of all operations satisfies EA=I\mat{E}\mat{A} = \mat{I}, hence E=A−1\mat{E} = \mat{A}\inv, and the right half, initially I\mat{I}, ends as EI=A−1\mat{E}\mat{I} = \mat{A}\inv. For example,

[21101101]→R2−12R1[2110012−121]→R1−2R2[202−2012−121]→12R1, 2R2[101−101−12].\begin{aligned} \left[\begin{array}{cc|cc} 2 & 1 & 1 & 0 \\ 1 & 1 & 0 & 1 \end{array}\right] &\xrightarrow{R_2 - \frac12 R_1} \left[\begin{array}{cc|cc} 2 & 1 & 1 & 0 \\ 0 & \tfrac12 & -\tfrac12 & 1 \end{array}\right] \\ &\xrightarrow{R_1 - 2R_2} \left[\begin{array}{cc|cc} 2 & 0 & 2 & -2 \\ 0 & \tfrac12 & -\tfrac12 & 1 \end{array}\right] \xrightarrow{\frac12 R_1,\ 2R_2} \left[\begin{array}{cc|cc} 1 & 0 & 1 & -1 \\ 0 & 1 & -1 & 2 \end{array}\right]. \end{aligned}

Rearranging EN⋯E1A=I\mat{E}_N\cdots\mat{E}_1\mat{A} = \mat{I} also yields A=E1−1⋯EN−1\mat{A} = \mat{E}_1\inv\cdots\mat{E}_N\inv: 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 A−1\mat{A}\inv can be calculated does not mean it should be. To solve Ax=b\mat{A}\vb{x} = \vb{b}, route x=A−1b\vb{x} = \mat{A}\inv\vb{b} loses for three reasons.

  1. Cost. Forming the inverse costs 2n32n^3 flops, three times factorization. With many right-hand sides, cost per system equalizes (2n22n^2 in both), but factorization is never worse.
  2. Accuracy. LU with partial pivoting is backward stable in practice: x^\hat{\vb{x}} solves a nearby system exactly and relative residual is on the order of uu. With the inverse, b−Ax^≈(I−AX^) b\vb{b} - \mat{A}\hat{\vb{x}} \approx (\mat{I} - \mat{A}\hat{\mat{X}})\,\vb{b}, and since each column of computed inverse X^\hat{\mat{X}} has its own error, that residual can reach the order of κ(A) u ∥b∥\kappa(\mat{A})\,u\,\norm{\vb{b}}. Forward error is on the order of κ(A)u\kappa(\mat{A})u in both, but the inverse is usually worse.
  3. Structure. Real matrices are often sparse or banded, as are their LU factors to a similar degree. Their inverses are dense. Tridiagonal matrix tridiag⁡(−1,2,−1)\operatorname{tridiag}(-1, 2, -1) of the one-dimensional heat equation has bidiagonal factors computed and applied in O(n)\bigO(n), whereas every inverse entry is nonzero: (A−1)ij=min⁡(i,j) (n+1−max⁡(i,j))/(n+1)(\mat{A}\inv)_{ij} = \min(i,j)\,\big(n + 1 - \max(i,j)\big)/(n+1). With a million unknowns, factorization takes a few million numbers and the inverse a trillion.
InteractiveFactor once, solve many times
Cost in flops to solve kk systems with the same matrix 1 000×1 0001\,000 \times 1\,000
  • LU once + k substitutions
  • inverse + k products A⁻¹b
  • eliminate again each time
Each new system costs 2n22n^2 with LU and 2n3/3+2n22n^3/3 + 2n^2 when eliminating again: about n/3n/3 times more. With these values, factorization is 76.9% of the LU route's total cost.
Accuracy measured in double precision: 50×5050 \times 50 matrices with prescribed κ(A)\kappa(\mat{A})
  • LU: relative residual
  • inverse: relative residual
  • LU: relative error
  • inverse: relative error
  • reference κ(A)·u
Relative residual ∥b−Ax^∥/(∥A∥∥x^∥)\norm{\vb{b} - \mat{A}\hat{\vb{x}}} / (\norm{\mat{A}}\norm{\hat{\vb{x}}}): the backward error. Re-eliminating each time performs exactly the same operations as reusing LU, so its accuracy is LU's.
Cost
1 000
100
Accuracy
10¹⁰
Flops for these nn and kk
LU route8.7×1088.7 \times 10^{8}
Inverse route2.2×1092.2 \times 10^{9}
Eliminate each time6.7×10106.7 \times 10^{10}
Eliminate / LU× 77.2\times\, 77.2
Inverse / LU× 2.54\times\, 2.54
Relative residual with κ(A)=1010\kappa(\mat{A}) = 10^{10}
With LU…\ldots
With A−1b\mat{A}\inv\vb{b}…\ldots
Inverse / LU…\ldots
Top: flop cost of solving kk systems with the same n×nn \times n matrix by three routes: repeat elimination (kk times 23n3+2n2\tfrac23 n^3 + 2n^2), factor once and reuse LU (23n3+2kn2\tfrac23 n^3 + 2kn^2), or compute the explicit inverse (2n3+2kn22n^3 + 2kn^2). Move kk: inversion initially costs three times LU and converges toward it; repeated elimination separates from both. Bottom: a real double-precision experiment with 50×5050 \times 50 matrices of prescribed condition number: LU relative residual stays near 10−1610^{-16} for any κ(A)\kappa(\mat{A}), the residual of A−1b\mat{A}\inv\vb{b} grows with κ(A)\kappa(\mat{A}), and both errors follow reference κ(A)u\kappa(\mat{A})u.

When is computing an inverse legitimate? When you need its entries, rather than its product with a vector. For example, the diagonal of (X⊤X)−1(\mat{X}\T\mat{X})\inv gives linear-regression coefficient variances. Even then calculate through factorization, solving with columns of I\mat{I} (or Cholesky if symmetric positive definite). For tiny fixed dimensions, such as 3×33 \times 3 inverses in graphics or robotics, closed formulas are reasonable when the matrix is well conditioned.

Implementation from scratch

The first lab implements PA=LU\mat{P}\mat{A} = \mat{L}\mat{U} with partial pivoting and both substitutions. The loop over kk 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.

[ ]LU with partial pivoting from scratchBrowser
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 34,12,14,−27,−37,13\tfrac34, \tfrac12, \tfrac14, -\tfrac27, -\tfrac37, \tfrac13, all with absolute value at most 11. Now compare with SciPy. Watch its convention: scipy.linalg.lu returns p, l, u with A=p l u\mat{A} = \mat{p}\,\mat{l}\,\mat{u}, so our P\mat{P} is its p⊤\mat{p}\T.

[ ]Comparison with SciPyBrowser
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 ∥PA−LU∥/∥A∥\norm{\mat{P}\mat{A} - \mat{L}\mat{U}}/\norm{\mat{A}} stays at rounding level (between uu and a few tens of uu, growing slowly with nn), and factors match LAPACK. Now reproduce the failure without pivoting:

[ ]The 1e-20 pivotBrowser
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/εu/\eps:

[ ]How many digits a small pivot costsBrowser
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 u/εu/\eps until it saturates on the order of 11, 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 ρ\rho from max⁡∣uij∣\max\abs{u_{ij}}:

[ ]Growth: Wilkinson versus random matricesBrowser
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 n=60n = 60 relative error is on the order of 11 on a matrix with κ(W)≈27\kappa(\mat{W}) \approx 27: growth 2592^{59} has consumed all 53 mantissa bits. Random matrices, by contrast, grow little and below n\sqrt{n}.

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 max⁡(m,n) εmaˊq max⁡∣aij∣\max(m, n)\,\eps_{\text{máq}}\,\max\abs{a_{ij}}, the order of accumulated rounding noise. This is relative tolerance: multiplying the matrix by 10−610^{-6} must not change its rank.

[ ]Reduced row echelon form and the general solutionBrowser
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 xp\vb{x}_p and the two special solutions as columns of N\mat{N}. For comparison with exact arithmetic, SymPy computes reduced form over rationals. An innocent-looking matrix shows why tolerance is not optional: with entries 0.1,0.2,…,0.90.1, 0.2, \dots, 0.9, not exactly representable in binary, the matrix has rational rank 22, 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.

[ ]Exact versus floating pointBrowser
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, U\mat{U} in the upper triangle and the strict part of L\mat{L} 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.

[ ]lu_factor y lu_solveBrowser
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 A⊤x=b\mat{A}\T\vb{x} = \vb{b} because A⊤=U⊤L⊤P\mat{A}\T = \mat{U}\T\mat{L}\T\mat{P}: 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:

[ ]Factor once versus factor every timeBrowser
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 kk 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 kk calls is paid kk times and is more significant in Pyodide without optimized BLAS. If all kk columns are available at once, np.linalg.solve(A, B) with matrix B\mat{B} 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:

[ ]Sparse factors, dense inverseBrowser
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 log⁡10κ(A)\log_{10}\kappa(\mat{A}) fewer if the matrix is ill-conditioned (in the next cell, with κ(A)=104\kappa(\mat{A}) = 10^4, about 4). But residual r=b−Ax^\vb{r} = \vb{b} - \mat{A}\hat{\vb{x}}, computed in double precision, can correct it by solving Ad=r\mat{A}\vb{d} = \vb{r} with the same cheap factorization: iterative refinement. As long as κ(A)\kappa(\mat{A}) is not too large for single precision, each iteration gains several digits:

[ ]Mixed-precision iterative refinementBrowser
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 κ(A)u≈10−12\kappa(\mat{A})u \approx 10^{-12}. 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 B×n×nB \times n \times n. The next cell needs the local lab:

[ ]LU on CPU and GPU, and GPU refinementLocal GPU
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.")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 n=4000n = 4000, 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

QuizRead reduced row echelon form
A system of 3 equations in 5 unknowns has rref⁡([A∣b])=[1200−1300102−1000114]\operatorname{rref}([\mat{A} \mid \vb{b}]) = \left[\begin{array}{ccccc|c} 1 & 2 & 0 & 0 & -1 & 3 \\ 0 & 0 & 1 & 0 & 2 & -1 \\ 0 & 0 & 0 & 1 & 1 & 4 \end{array}\right]. How many solutions and free variables does it have?
QuizSingular but solvable
A∈R3×3\mat{A} \in \R^{3\times 3} is singular and Ax=b\mat{A}\vb{x} = \vb{b} is known to have solution x=(1,2,3)\vb{x} = (1, 2, 3). How many solutions does the system have?
NumericA multiplier
Apply Gaussian elimination without swaps to A=[121381041]\mat{A} = \begin{bmatrix} 1 & 2 & 1 \\ 3 & 8 & 1 \\ 0 & 4 & 1 \end{bmatrix}. What is multiplier ℓ32\ell_{32}, entry (3,2)(3, 2) of L\mat{L}?
QuizInverse of an elimination chain
E21\mat{E}_{21} subtracts twice row 1 from row 2, and E32\mat{E}_{32} subtracts three times row 2 from row 3 (all 3×33 \times 3). What is (E32E21)−1(\mat{E}_{32}\mat{E}_{21})\inv?
NumericFactorization cost
Estimate in GFLOP (10910^9 operations) the dominant cost term for LU factorization of a dense 3000×30003000 \times 3000 matrix.
NumericWilkinson growth
The Wilkinson matrix W6∈R6×6\mat{W}_6 \in \R^{6\times 6} has ones on its diagonal and last column, −1-1 below the diagonal and zeros elsewhere. Apply elimination with partial pivoting. What is the final pivot u66u_{66}?
QuizA near-zero pivot
You factor a 6×66 \times 6 matrix with entries on the order of 1 using partial pivoting in double precision. Absolute pivot values are 2.05, 0.57, 1.33, 1.31, 4.4×10−162.05,\ 0.57,\ 1.33,\ 1.31,\ 4.4 \times 10^{-16} and 2.2×10−162.2 \times 10^{-16}. What do you conclude?
QuizWhy not inv(A) @ b?
You will solve Ax=b\mat{A}\vb{x} = \vb{b} with dense A\mat{A} of size n×nn \times n. Why is np.linalg.inv(A) @ b worse than np.linalg.solve(A, b)?
CodeFactor once, solve many times
Implement lu_solve_many(A, B): factor A (n×nn \times n) once with partial pivoting and solve AX=B\mat{A}\mat{X} = \mat{B} for all columns of B (n×kn \times k), using forward and backward substitution (preferably vectorized across kk 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)
  pass
Shift+Enter to run

Summary

Key idea
Solving Ax=b\mat{A}\vb{x} = \vb{b} means factorizing: Gaussian elimination is a product of elementary matrices recorded as PA=LU\mat{P}\mat{A} = \mat{L}\mat{U}, costing 23n3\tfrac{2}{3}n^3 once and 2n22n^2 per right-hand side, requiring pivoting for stability and making calculation of A−1\mat{A}\inv unnecessary and inadvisable.
  • Three outcomes. Solutions form xp+null⁡(A)\vb{x}_p + \nullsp(\mat{A}): none, one or infinitely many. Existence is determined by b\vb{b} (is it in the column space?); uniqueness only by A\mat{A} (independent columns?). A singular square matrix never gives a unique solution, and b\vb{b} decides between none and infinitely many.
  • Reduced row echelon form. It is unique and reveals everything: pivots, free variables, row 0=10 = 1 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 kk form a Gauss transformation, and the product of their inverses places each multiplier in position in L\mat{L}. 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 (∣ℓik∣≤1\abs{\ell_{ik}} \le 1) gives PA=LU\mat{P}\mat{A} = \mat{L}\mat{U} and, barring pathological matrices such as Wilkinson’s, a backward-stable algorithm.
  • Do not invert. The inverse costs three times more, can leave residuals κ(A)\kappa(\mat{A}) times larger and is dense even if A\mat{A} is not. Factor once, reuse for each right-hand side and, if speed matters, factor at low precision and refine at high precision.