TExcelTAD
Home › Linear Algebra & Matrix Theory › Numerical Linear Algebra: LU, QR and Conditioning

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 ε≈2.2⋅10−16\varepsilon \approx 2.2 \cdot 10^{-16}. Every arithmetic operation may introduce a relative error of up to ε/2\varepsilon/2. 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 LL gives A=LUA = LU with UU upper triangular (the elementary matrices of the elimination, multiplied together and inverted). Once you have it, solving Ax=bA\mathbf{x} = \mathbf{b} is two cheap triangular solves, Ly=bL\mathbf{y} = \mathbf{b} then Ux=yU\mathbf{x} = \mathbf{y}, so factor once (≈23n3\approx \frac{2}{3}n^3 operations) and reuse it for many right-hand sides (≈2n2\approx 2n^2 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 PA=LUPA = LU with a permutation matrix PP. This is what every library does.

python · try it yourself
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 101710^{17} and x1x_1 comes out completely wrong. Swapping the rows first gives the right answer.

QR factorization

A=QRA = QR with QQ orthogonal and RR upper triangular (Gram-Schmidt in exact arithmetic; Householder reflections in practice). Orthogonal matrices never amplify errors (∥Qx∥=∥x∥\lVert Q\mathbf{x} \rVert = \lVert \mathbf{x} \rVert), so QR is the stable choice for least squares (solve Rx=QTbR\mathbf{x} = Q^T\mathbf{b}) and is the core of the QR algorithm for eigenvalues. It costs about twice as much as LU.

Factorization Form Cost (n×nn \times n) Typical use
LU (partial pivoting) PA=LUPA = LU ≈23n3\approx \frac{2}{3}n^3 general square systems, determinants
Cholesky A=LLTA = LL^T ≈13n3\approx \frac{1}{3}n^3 symmetric positive definite systems
QR (Householder) A=QRA = QR ≈43⋅n3\approx \frac{4}{3} \cdot n^3 least squares, eigenvalue algorithms
SVD A=UΣVTA = U \Sigma V^T ≈10n3\approx 10n^3 or more rank, pseudoinverse, ill-conditioned problems (SVD)

Tip: Never compute A−1A^{-1} just to solve Ax=bA\mathbf{x} = \mathbf{b}. np.linalg.solve (LU) is about three times cheaper and more accurate than np.linalg.inv(A) @ b.

The condition number

How much can a small change in b\mathbf{b} change the solution of Ax=bA\mathbf{x} = \mathbf{b}? If Ax=bA\mathbf{x} = \mathbf{b} and A(x+δx)=b+δbA(\mathbf{x} + \delta\mathbf{x}) = \mathbf{b} + \delta\mathbf{b}, then δx=A−1δb\delta\mathbf{x} = A^{-1}\delta\mathbf{b} and

∥δx∥∥x∥≤κ(A)⋅∥δb∥∥b∥,κ(A)=∥A∥∥A−1∥=σmax⁡/σmin⁡(2-norm)\frac{\lVert \delta\mathbf{x} \rVert}{\lVert \mathbf{x} \rVert} \le \kappa(A) \cdot \frac{\lVert \delta\mathbf{b} \rVert}{\lVert \mathbf{b} \rVert}, \qquad \kappa(A) = \lVert A \rVert \lVert A^{-1} \rVert = \sigma_{\max} / \sigma_{\min} \quad \text{(2-norm)}

The condition number κ(A)\kappa(A) is a property of the problem, not of the algorithm. Rule of thumb: with ε≈10−16\varepsilon \approx 10^{-16}, expect to lose about log⁡10κ(A)\log_{10} \kappa(A) of your 16 digits, even with a perfect (backward-stable) algorithm. κ=1\kappa = 1 for orthogonal matrices; κ=∞\kappa = \infty for singular ones.

Hilbert matrices: a classic stress test

The Hilbert matrix Hij=1/(i+j−1)H_{ij} = 1/(i + j - 1) is symmetric positive definite and perfectly invertible, yet its condition number explodes. We choose x=(1,…,1)\mathbf{x} = (1, \ldots, 1), compute b=Hx\mathbf{b} = H\mathbf{x}, then solve for x\mathbf{x} and see how much is lost:

python · try it yourself
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 n=12n = 12 the condition number passes 1/ε≈4.5⋅10151/\varepsilon \approx 4.5 \cdot 10^{15} and the computed solution has no correct digits, although solve did its job perfectly well: the residual Hx−bH\mathbf{x} - \mathbf{b} is tiny. The problem itself cannot be answered in double precision. Exact rational arithmetic shows the matrix is fine mathematically:

python · try it yourself
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 10−7810^{-78}), but not zero. A small determinant alone does not mean ill-conditioning (0.1⋅I0.1 \cdot I has det 10−n10^{-n} and κ=1\kappa = 1); the ratio σmax⁡/σmin⁡\sigma_{\max}/\sigma_{\min} is what matters.

What to do about ill-conditioning

  • Reformulate. Polynomial fitting with the monomials 1,x,x2,…1, x, x^2, \ldots produces Hilbert-like matrices; orthogonal polynomial bases (Legendre, Chebyshev) are far better conditioned.
  • Scale. Features of wildly different sizes (metres and nanometres) inflate κ\kappa; standardize them.
  • Regularize. Ridge regression solves (ATA+λI)x=ATb(A^T A + \lambda I)\mathbf{x} = A^T\mathbf{b}, raising σmin⁡\sigma_{\min}.
  • Use the SVD to see which directions are lost and drop them (truncated SVD).
  • Avoid squaring κ\kappa: normal equations ATAA^T A have κ(A)2\kappa(A)^2, QR or SVD keep κ(A)\kappa(A) (Least Squares).

In software

  • NumPy and SciPy call LAPACK: np.linalg.solve (LU with partial pivoting), scipy.linalg.lu_factor/lu_solve to reuse a factorization, cho_factor for 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 κ\kappa (Sparse Linear Algebra).
  • Machine learning. Low-precision training (float16, bfloat16 have ε≈10−3\varepsilon \approx 10^{-3} and 10−210^{-2}) makes conditioning matter even more; normalization layers and careful initialization keep κ\kappa 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 LL and UU (no pivoting) for A=[2168]A = \begin{bmatrix} 2 & 1 \\ 6 & 8 \end{bmatrix}.

Answer

L=[1031]L = \begin{bmatrix} 1 & 0 \\ 3 & 1 \end{bmatrix}, U=[2105]U = \begin{bmatrix} 2 & 1 \\ 0 & 5 \end{bmatrix}.

Solution

The multiplier is 6/2=36/2 = 3: row 2−3⋅row 1=(0,8−3)=(0,5)\text{row } 2 - 3 \cdot \text{row } 1 = (0, 8 - 3) = (0, 5). LL stores the multiplier below its diagonal of ones.

Exercise 2: Condition number of a diagonal matrix

What is κ2\kappa_2 of diag⁡(100,0.01)\operatorname{diag}(100, 0.01)? About how many digits might you lose solving with it?

Answer

κ=104\kappa = 10^4; about 4 digits.

Solution

The singular values of a diagonal matrix are the absolute values of its entries: κ=100/0.01=104\kappa = 100/0.01 = 10^4, and log⁡10104=4\log_{10} 10^4 = 4.

Exercise 3: Sensitivity

κ(A)=106\kappa(A) = 10^6 and b\mathbf{b} is measured with relative error 10−810^{-8}. What is the worst-case relative error in x\mathbf{x}?

Answer

10−210^{-2}.

Solution

∥δx∥/∥x∥≤κ⋅∥δb∥/∥b∥=106⋅10−8=10−2\lVert \delta\mathbf{x} \rVert/\lVert \mathbf{x} \rVert \le \kappa \cdot \lVert \delta\mathbf{b} \rVert/\lVert \mathbf{b} \rVert = 10^6 \cdot 10^{-8} = 10^{-2}, that is 1%.

Exercise 4: Reuse a factorization (code)

Factor A=[43034−10−14]A = \begin{bmatrix} 4 & 3 & 0 \\ 3 & 4 & -1 \\ 0 & -1 & 4 \end{bmatrix} once with SciPy and solve for b=(7,6,3)\mathbf{b} = (7, 6, 3) and b=(1,0,0)\mathbf{b} = (1, 0, 0).

Answer

x=(1,1,1)\mathbf{x} = (1, 1, 1) for the first; x=(15,−12,−3)/24=(0.625,−0.5,−0.125)\mathbf{x} = (15, -12, -3)/24 = (0.625, -0.5, -0.125) for the second.

Solution

lu_factor does the 23n3\frac{2}{3}n^3 work once; each lu_solve is two triangular solves. The second solution is the first column of A−1=adj⁡(A)/det⁡AA^{-1} = \operatorname{adj}(A)/\det A. Here det⁡A=4(16−1)−3(12−0)=24\det A = 4(16 - 1) - 3(12 - 0) = 24, and the first column of the adjugate is the cofactors (15,−12,−3)(15, -12, -3), so x=(15,−12,−3)/24\mathbf{x} = (15, -12, -3)/24.

python · try it yourself
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?

  1. To make LL symmetric
  2. To avoid dividing by tiny pivots, which would amplify rounding errors
  3. To reduce the cost below n3n^3
  4. Because UU must be orthogonal

A matrix has condition number 101210^{12}. Roughly how many correct digits can you expect in double precision?

  1. 16
  2. 12
  3. 4
  4. 0

Which statement about the Hilbert matrix H12H_{12} is true?

  1. It is singular
  2. It is invertible, but so ill-conditioned that double precision gives no correct digits
  3. Its condition number is 12
  4. LU without pivoting solves it exactly in floating point