LU Factorization
Gaussian elimination, the method taught in every linear algebra course, is really a matrix factorization: it writes with unit lower triangular and upper triangular. Separating the factorization from the solve is what makes it efficient: factor once in , then solve for any number of right-hand sides in each.
Elimination as a factorization
Elimination subtracts multiples of row from rows to create zeros below the pivot . Collect the multipliers in a lower triangular matrix with ones on the diagonal: that is . What remains of is .
import numpy as np
def lu_nopivot(A):
n = A.shape[0]
U = A.astype(float).copy()
L = np.eye(n)
for k in range(n - 1):
for i in range(k + 1, n):
L[i, k] = U[i, k] / U[k, k] # multiplier
U[i, k:] -= L[i, k] * U[k, k:] # eliminate
return L, U
A = np.array([[2.0, 1, 1], [4, -6, 0], [-2, 7, 2]])
L, U = lu_nopivot(A)
print("L =\n", L)
print("U =\n", U)
print("L @ U == A:", np.allclose(L @ U, A))L =
[[ 1. 0. 0.]
[ 2. 1. 0.]
[-1. -1. 1.]]
U =
[[ 2. 1. 1.]
[ 0. -8. -2.]
[ 0. 0. 1.]]
L @ U == A: True
Solving with the factors
becomes :
- Solve by forward substitution.
- Solve by backward substitution (Triangular Systems).
The factorization also gives the determinant almost for free: (times for row swaps).
import numpy as np
from scipy.linalg import lu_factor, lu_solve, solve_triangular
A = np.array([[2.0, 1, 1], [4, -6, 0], [-2, 7, 2]])
B = np.array([[5.0, 1], [-2, 0], [9, 3]]) # two right-hand sides
lu, piv = lu_factor(A) # factor once
X = lu_solve((lu, piv), B) # reuse for both columns
print("X =\n", X)
print("residual:", np.max(np.abs(A @ X - B)))
print("det from U:", np.prod(np.diag(lu)) * (-1) ** np.sum(piv != np.arange(3)), " np.linalg.det:", round(np.linalg.det(A), 10))X =
[[ 1. -0.375]
[ 1. -0.25 ]
[ 2. 2. ]]
residual: 0.0
det from U: -16.0 np.linalg.det: -16.0
Vectorized elimination
The inner loop over rows is an outer product update of the trailing submatrix, . Written that way it runs much faster in NumPy, and real libraries go further by working on blocks of columns at once so that most work happens in matrix-matrix products.
import numpy as np
def lu_outer(A):
n = A.shape[0]
U = A.astype(float).copy()
L = np.eye(n)
for k in range(n - 1):
L[k + 1:, k] = U[k + 1:, k] / U[k, k]
U[k + 1:, k:] -= np.outer(L[k + 1:, k], U[k, k:])
return L, U
rng = np.random.default_rng(0)
A = rng.normal(size=(200, 200)) + 20 * np.eye(200)
L, U = lu_outer(A)
print(f"max |LU - A| = {np.max(np.abs(L @ U - A)):.1e}, U upper triangular: {np.allclose(U, np.triu(U))}")max |LU - A| = 3.2e-14, U upper triangular: True
When it breaks down
Elimination without row exchanges fails if a pivot is zero, even for a nonsingular matrix like , and is inaccurate when a pivot is tiny. The cure is partial pivoting (Row Pivoting), which gives .
In software
scipy.linalg.lu(A)returns ;lu_factor/lu_solvekeep the compact LAPACK form for repeated solves.np.linalg.solve(A, b)calls LAPACKgesv, which is LU with partial pivoting followed by two triangular solves.- Never compute
np.linalg.inv(A) @ b: it costs about three times as much as a solve and is less accurate.
Exercises
Exercise 1: Factor by hand
Find the LU factorization of .
Answer
, .
Solution
Multiplier ; row 2 minus row 1 gives .
Exercise 2: Many right-hand sides
You must solve for 100 vectors , with . Roughly how many flops does factoring once and reusing save compared with 100 separate solves?
Answer
About flops.
Solution
Each separate solve repeats the -flop factorization; the triangular solves ( each) are needed either way.
Exercise 3: A zero pivot (code)
Run lu_nopivot on and then scipy.linalg.lu. What happens?
Answer
The no-pivot version divides by zero (infinite or NaN entries); SciPy swaps the rows and succeeds.
Solution
import numpy as np
from scipy.linalg import lu
A = np.array([[0.0, 1], [1, 1]])
with np.errstate(all="ignore"):
U = A.copy(); m = U[1, 0] / U[0, 0]; U[1] -= m * U[0]
print("no pivoting: multiplier", m, "U row 2", U[1])
P, L, U = lu(A)
print("P =", P.tolist(), "L =", L.tolist(), "U =", U.tolist())no pivoting: multiplier inf U row 2 [ nan -inf]
P = [[0.0, 1.0], [1.0, 0.0]] L = [[1.0, 0.0], [0.0, 1.0]] U = [[1.0, 1.0], [0.0, 1.0]]
Test yourself
In from Gaussian elimination, the entries of below the diagonal are…
- the pivots
- the multipliers
- zeros
- the entries of
After factoring once, solving for a new right-hand side costs…
Why avoid np.linalg.inv(A) @ b?
- It gives a different answer in exact arithmetic
- It costs more and is less accurate than solving
- It only works for symmetric
- It is not implemented