Numerical Linear Algebra: LU, QR and Conditioning
On paper, Gaussian elimination gives exact answers. On a computer every number has about 16 significant digits, and some problems amplify the rounding errors enormously. Numerical linear algebra is about factorizations that are fast and stable, and about the condition number, which tells you how many digits you can trust.
Floating point in one paragraph
A float64 stores about 15–16 significant decimal digits; the gap between 1 and the next representable number is machine epsilon . Every arithmetic operation may introduce a relative error of up to . One rounding is harmless; the question is whether an algorithm, or the problem itself, magnifies them.
LU factorization: Gaussian elimination, recorded
Gaussian elimination subtracts multiples of rows. Recording the multipliers in a lower triangular gives with upper triangular (the elementary matrices of the elimination, multiplied together and inverted). Once you have it, solving is two cheap triangular solves, then , so factor once ( operations) and reuse it for many right-hand sides ( each).
Pivoting. Plain elimination divides by the pivot. A tiny pivot creates huge multipliers that swamp the other entries. Partial pivoting swaps rows so that the largest available entry (in absolute value) is the pivot, giving with a permutation matrix . This is what every library does.
import numpy as np
import scipy.linalg as la
eps = 1e-17
A = np.array([[eps, 1.0], [1.0, 1.0]])
b = np.array([1.0, 2.0]) # exact solution is very close to (1, 1)
# elimination without pivoting
m = A[1, 0] / A[0, 0] # multiplier 1e17
u22 = A[1, 1] - m * A[0, 1]
y2 = b[1] - m * b[0]
x2 = y2 / u22
x1 = (b[0] - A[0, 1] * x2) / A[0, 0]
print("no pivoting :", [float(x1), float(x2)])
P, L, U = la.lu(A) # SciPy returns A = P L U
print("with pivoting:", la.lu_solve(la.lu_factor(A), b))
print("P =", P.tolist(), " L =", np.round(L, 3).tolist())
print("P L U = A:", np.allclose(P @ L @ U, A))no pivoting : [0.0, 1.0]
with pivoting: [1. 1.]
P = [[0.0, 1.0], [1.0, 0.0]] L = [[1.0, 0.0], [0.0, 1.0]]
P L U = A: True
Without pivoting, the 1 in position (2, 2) is lost next to and comes out completely wrong. Swapping the rows first gives the right answer.
QR factorization
with orthogonal and upper triangular (Gram-Schmidt in exact arithmetic; Householder reflections in practice). Orthogonal matrices never amplify errors (), so QR is the stable choice for least squares (solve ) and is the core of the QR algorithm for eigenvalues. It costs about twice as much as LU.
| Factorization | Form | Cost () | Typical use |
|---|---|---|---|
| LU (partial pivoting) | general square systems, determinants | ||
| Cholesky | symmetric positive definite systems | ||
| QR (Householder) | least squares, eigenvalue algorithms | ||
| SVD | or more | rank, pseudoinverse, ill-conditioned problems (SVD) |
Tip: Never compute just to solve .
np.linalg.solve(LU) is about three times cheaper and more accurate thannp.linalg.inv(A) @ b.
The condition number
How much can a small change in change the solution of ? If and , then and
The condition number is a property of the problem, not of the algorithm. Rule of thumb: with , expect to lose about of your 16 digits, even with a perfect (backward-stable) algorithm. for orthogonal matrices; for singular ones.
Hilbert matrices: a classic stress test
The Hilbert matrix is symmetric positive definite and perfectly invertible, yet its condition number explodes. We choose , compute , then solve for and see how much is lost:
import numpy as np
from scipy.linalg import hilbert
for n in (4, 8, 12, 14):
H = hilbert(n)
x_true = np.ones(n)
b = H @ x_true
x = np.linalg.solve(H, b)
err = np.max(np.abs(x - x_true))
kappa = np.linalg.cond(H)
print(f"n={n:2d} cond = {kappa:8.1e} max error = {err:8.1e} "
f"digits lost ≈ {np.log10(kappa):4.1f}")n= 4 cond = 1.6e+04 max error = 6.1e-13 digits lost ≈ 4.2
n= 8 cond = 1.5e+10 max error = 4.4e-07 digits lost ≈ 10.2
n=12 cond = 1.8e+16 max error = 3.9e-01 digits lost ≈ 16.3
n=14 cond = 4.9e+17 max error = 2.7e+01 digits lost ≈ 17.7
At the condition number passes and the computed solution has no correct digits, although solve did its job perfectly well: the residual is tiny. The problem itself cannot be answered in double precision. Exact rational arithmetic shows the matrix is fine mathematically:
from sympy import Matrix, Rational, ones
n = 12
H = Matrix(n, n, lambda i, j: Rational(1, i + j + 1))
b = H * ones(n, 1)
x = H.LUsolve(b)
print("exact solution all ones:", x == ones(n, 1))
d = H.det()
print("det(H_12) is exact rational; as a float:", f"{float(d):.3e}")
print("its denominator has", len(str(d.q)), "digits")exact solution all ones: True
det(H_12) is exact rational; as a float: 2.638e-78
its denominator has 78 digits
The determinant is a tiny positive rational number (about ), but not zero. A small determinant alone does not mean ill-conditioning ( has det and ); the ratio is what matters.
What to do about ill-conditioning
- Reformulate. Polynomial fitting with the monomials produces Hilbert-like matrices; orthogonal polynomial bases (Legendre, Chebyshev) are far better conditioned.
- Scale. Features of wildly different sizes (metres and nanometres) inflate ; standardize them.
- Regularize. Ridge regression solves , raising .
- Use the SVD to see which directions are lost and drop them (truncated SVD).
- Avoid squaring : normal equations have , QR or SVD keep (Least Squares).
In software
- NumPy and SciPy call LAPACK:
np.linalg.solve(LU with partial pivoting),scipy.linalg.lu_factor/lu_solveto reuse a factorization,cho_factorfor SPD systems,qr,svd(SciPy Linear Algebra, Decompositions). - Sparse problems (finite elements, graphs, PageRank) use sparse LU or iterative methods like conjugate gradients whose speed depends on (Sparse Linear Algebra).
- Machine learning. Low-precision training (float16, bfloat16 have and ) makes conditioning matter even more; normalization layers and careful initialization keep moderate.
- Games and physics. Constraint solvers iterate instead of factoring, and near-singular configurations (aligned joints) show up as jitter.
Exercises
Exercise 1: LU by hand
Find and (no pivoting) for .
Answer
, .
Solution
The multiplier is : . stores the multiplier below its diagonal of ones.
Exercise 2: Condition number of a diagonal matrix
What is of ? About how many digits might you lose solving with it?
Answer
; about 4 digits.
Solution
The singular values of a diagonal matrix are the absolute values of its entries: , and .
Exercise 3: Sensitivity
and is measured with relative error . What is the worst-case relative error in ?
Answer
.
Solution
, that is 1%.
Exercise 4: Reuse a factorization (code)
Factor once with SciPy and solve for and .
Answer
for the first; for the second.
Solution
lu_factor does the work once; each lu_solve is two triangular solves. The second solution is the first column of . Here , and the first column of the adjugate is the cofactors , so .
import numpy as np
from scipy.linalg import lu_factor, lu_solve
A = np.array([[4.0, 3, 0], [3, 4, -1], [0, -1, 4]])
f = lu_factor(A)
print(lu_solve(f, [7.0, 6, 3]), np.round(lu_solve(f, [1.0, 0, 0]), 4))
print("det A =", round(float(np.linalg.det(A)), 6))[1. 1. 1.] [ 0.625 -0.5 -0.125]
det A = 24.0
Test yourself
Why do libraries use partial pivoting in LU?
- To make symmetric
- To avoid dividing by tiny pivots, which would amplify rounding errors
- To reduce the cost below
- Because must be orthogonal
A matrix has condition number . Roughly how many correct digits can you expect in double precision?
- 16
- 12
- 4
- 0
Which statement about the Hilbert matrix is true?
- It is singular
- It is invertible, but so ill-conditioned that double precision gives no correct digits
- Its condition number is 12
- LU without pivoting solves it exactly in floating point