LUP Decomposition, Solving and Inverting
The LU decomposition of the previous lesson breaks down on a zero pivot and misbehaves on a tiny one. The cure is old and simple: before eliminating column , swap the row with the largest entry in that column into the pivot position. Recording the swaps as a permutation gives the LUP decomposition , which exists for every invertible matrix and is what numerical libraries actually compute. This lesson develops it, uses it to solve systems and to invert matrices, and shows that inverting a matrix is no harder than multiplying two.
A tiny pivot in floating point
Take the system
whose solution is extremely close to . LU without exchanges uses the pivot , the multiplier , and computes , which rounds to : the information in the entry 1 is lost. Swapping the rows first makes the multiplier and nothing is lost.
def solve_2x2(a, b, pivot):
a = [row[:] for row in a]; b = b[:]
if pivot and abs(a[1][0]) > abs(a[0][0]):
a[0], a[1] = a[1], a[0]; b[0], b[1] = b[1], b[0]
l = a[1][0] / a[0][0]
u11 = a[1][1] - l * a[0][1]
y1 = b[1] - l * b[0]
x1 = y1 / u11
x0 = (b[0] - a[0][1] * x1) / a[0][0]
return x0, x1
a, b = [[1e-20, 1.0], [1.0, 1.0]], [1.0, 2.0]
print("without pivoting:", solve_2x2(a, b, False))
print("with pivoting: ", solve_2x2(a, b, True))without pivoting: (0.0, 1.0)
with pivoting: (1.0, 1.0)
Without pivoting the answer for is completely wrong, although every single operation was rounded correctly. The matrix is perfectly well conditioned; the algorithm made it look ill conditioned. Partial pivoting keeps every multiplier at most 1 in absolute value, which in practice controls the growth of rounding errors (there are contrived matrices where the entries still grow like , but they essentially never occur).
The factorization
A permutation matrix has exactly one 1 in every row and column; reorders the rows of . Store it compactly as an array : row of is row of . The algorithm is LU-DECOMPOSE with a row exchange in front of each elimination step:
LUP-DECOMPOSE(A, n) // in place; returns pi with PA = LU
1 pi = [0, 1, ..., n - 1]
2 for k = 0 to n - 1
3 p = the row i >= k with the largest |A[i][k]|
4 if A[p][k] == 0
5 error "singular matrix"
6 swap rows k and p of A; swap pi[k] and pi[p]
7 for i = k + 1 to n - 1
8 A[i][k] = A[i][k] / A[k][k]
9 for j = k + 1 to n - 1
10 A[i][j] = A[i][j] - A[i][k] * A[k][j]
11 return piSwapping whole rows, including the multipliers already stored in the columns left of , keeps consistent with the permutation. If column has no nonzero entry from row down, the first columns of the current matrix are linearly dependent and is singular. So for an invertible the algorithm always succeeds: every invertible matrix has an LUP decomposition. The extra cost is comparisons in total, nothing against the updates.
To solve : since , the system is . Permute (the vector has entries ), then do forward and back substitution as before. As a bonus, , where is the number of actual swaps.
from fractions import Fraction
def lup_decompose(A):
n = len(A)
a = [[Fraction(x) for x in row] for row in A]
pi, swaps = list(range(n)), 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("singular matrix")
if p != k:
a[k], a[p] = a[p], a[k]
pi[k], pi[p] = pi[p], pi[k]
swaps += 1
print(f" column {k}: swap rows {k} and {p} (pivot {a[k][k]})")
for i in range(k + 1, n):
a[i][k] /= a[k][k]
for j in range(k + 1, n):
a[i][j] -= a[i][k] * a[k][j]
return a, pi, swaps
def lup_solve(a, pi, b):
n = len(b)
y = []
for i in range(n):
y.append(b[pi[i]] - sum(a[i][j] * y[j] for j in range(i)))
x = [Fraction(0)] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(a[i][j] * x[j] for j in range(i + 1, n))) / a[i][i]
return x
A = [[0, 2, 1], [1, -1, 3], [4, 2, -2]]
a, pi, swaps = lup_decompose(A)
print("pi =", pi)
for i in range(3):
print(" L row", [str(a[i][j]) if j < i else str(int(i == j)) for j in range(3)],
" U row", [str(a[i][j]) if j >= i else "0" for j in range(3)])
x = lup_solve(a, pi, [1, 12, 0])
det = (-1) ** swaps * a[0][0] * a[1][1] * a[2][2]
print("solution of Ax = (1, 12, 0):", [str(v) for v in x], " det A =", det) column 0: swap rows 0 and 2 (pivot 4)
column 1: swap rows 1 and 2 (pivot 2)
pi = [2, 0, 1]
L row ['1', '0', '0'] U row ['4', '2', '-2']
L row ['0', '1', '0'] U row ['0', '2', '1']
L row ['1/4', '-3/4', '1'] U row ['0', '0', '17/4']
solution of Ax = (1, 12, 0): ['2', '-1', '3'] det A = 34
The first column has a zero in the pivot position, so plain LU would fail at once; LUP swaps in the 4 and continues.
Inverting a matrix
The inverse satisfies , which is separate systems , one per column of the identity. With one LUP decomposition () and solves ( each), inversion takes time in total. In practice you rarely need itself: to compute , solving is both faster and more accurate.
from fractions import Fraction
def lup_decompose(A):
n = len(A)
a = [[Fraction(x) for x in row] for row in A]
pi = list(range(n))
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
a[k], a[p] = a[p], a[k]
pi[k], pi[p] = pi[p], pi[k]
for i in range(k + 1, n):
a[i][k] /= a[k][k]
for j in range(k + 1, n):
a[i][j] -= a[i][k] * a[k][j]
return a, pi
def lup_solve(a, pi, b):
n = len(b)
y = []
for i in range(n):
y.append(b[pi[i]] - sum(a[i][j] * y[j] for j in range(i)))
x = [Fraction(0)] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(a[i][j] * x[j] for j in range(i + 1, n))) / a[i][i]
return x
def inverse(A):
n = len(A)
a, pi = lup_decompose(A)
cols = [lup_solve(a, pi, [int(i == j) for i in range(n)]) for j in range(n)]
return [[cols[j][i] for j in range(n)] for i in range(n)]
A = [[0, 2, 1], [1, -1, 3], [4, 2, -2]]
X = inverse(A)
for row in X:
print(" " + " ".join(f"{str(v):>7}" for v in row))
I = [[sum(A[i][k] * X[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
print("A X == I:", I == [[int(i == j) for j in range(3)] for i in range(3)]) -2/17 3/17 7/34
7/17 -2/17 1/34
3/17 4/17 -1/17
A X == I: True
Inversion is as easy as multiplication
Is inversion inherently harder than multiplication? No: the two have the same asymptotic complexity.
Multiplication reduces to inversion. For matrices and , the block matrix below is always invertible, and its inverse contains the product:
Multiplying the two matrices gives the identity, which proves the formula. So an algorithm that inverts matrices in time multiplies matrices in time .
Inversion reduces to multiplication. Conversely, a divide-and-conquer inversion through Schur complements (for symmetric positive-definite matrices, and for any invertible by inverting and multiplying by ) inverts in time, where is the time to multiply, provided grows at least like and is reasonably regular. With Strassen's algorithm, matrices can be inverted in time.
The program checks the block identity on a small example.
from fractions import Fraction
def inverse(M): # Gauss-Jordan, exact
n = len(M)
a = [[Fraction(x) for x in row] + [Fraction(int(i == j)) for j in range(n)] for i, row in enumerate(M)]
for k in range(n):
p = next(i for i in range(k, n) if a[i][k] != 0)
a[k], a[p] = a[p], a[k]
a[k] = [v / a[k][k] for v in a[k]]
for i in range(n):
if i != k and a[i][k] != 0:
a[i] = [v - a[i][k] * w for v, w in zip(a[i], a[k])]
return [row[n:] for row in a]
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
n = 2
Z = [[0] * n for _ in range(n)]
I = [[int(i == j) for j in range(n)] for i in range(n)]
def block(rows):
return [sum((r[i] for r in row), []) for row in rows for i in range(n)]
big = block([[I, A, Z], [Z, I, B], [Z, Z, I]])
inv = inverse(big)
AB = [[int(inv[i][j]) for j in range(2 * n, 3 * n)] for i in range(n)]
print("top-right block of the inverse:", AB)
print("A B computed directly: ", [[sum(A[i][k] * B[k][j] for k in range(n)) for j in range(n)] for i in range(n)])top-right block of the inverse: [[19, 22], [43, 50]]
A B computed directly: [[19, 22], [43, 50]]
In C++
LUP decomposition and solving in double arithmetic, on a system whose first pivot position would be fine but whose second is zero without exchanges.
#include <cmath>
#include <cstdio>
#include <utility>
#include <vector>
using Matrix = std::vector<std::vector<double>>;
std::vector<int> lup_decompose(Matrix& a) {
int n = int(a.size());
std::vector<int> pi(n);
for (int i = 0; i < n; i++) pi[i] = i;
for (int k = 0; k < n; k++) {
int p = k;
for (int i = k + 1; i < n; i++) if (std::fabs(a[i][k]) > std::fabs(a[p][k])) p = i;
std::swap(a[k], a[p]);
std::swap(pi[k], pi[p]);
for (int i = k + 1; i < n; i++) {
a[i][k] /= a[k][k];
for (int j = k + 1; j < n; j++) a[i][j] -= a[i][k] * a[k][j];
}
}
return pi;
}
std::vector<double> lup_solve(const Matrix& a, const std::vector<int>& pi, const std::vector<double>& b) {
int n = int(a.size());
std::vector<double> x(n);
for (int i = 0; i < n; i++) {
x[i] = b[pi[i]];
for (int j = 0; j < i; j++) x[i] -= a[i][j] * x[j];
}
for (int i = n - 1; i >= 0; i--) {
for (int j = i + 1; j < n; j++) x[i] -= a[i][j] * x[j];
x[i] /= a[i][i];
}
return x;
}
int main() {
Matrix a = {{1, 2, 0, 3}, {2, 4, 1, 1}, {0, 1, 5, 2}, {3, 1, 2, 0}};
auto pi = lup_decompose(a);
std::printf("pi = %d %d %d %d\n", pi[0], pi[1], pi[2], pi[3]);
auto x = lup_solve(a, pi, {8, 10, -1, 3});
std::printf("x = %.6f %.6f %.6f %.6f\n", x[0], x[1], x[2], x[3]);
}pi = 3 1 2 0
x = 1.000000 2.000000 -1.000000 1.000000
Libraries call this routine getrf (factor) and getrs (solve) in LAPACK; NumPy's np.linalg.solve and SciPy's scipy.linalg.lu_factor use them. The Numerical Linear Algebra lesson discusses conditioning and stability further.
Test yourself
Which row does partial pivoting choose before eliminating column ?
- Row , always
- The row with the largest
- The row with the smallest nonzero entry in column
- A random row
With , how do you solve ?
- Solve , then , then permute
- Solve by forward substitution, then by back substitution
- Solve only
- Compute first
What is the running time of inverting an matrix with one LUP decomposition and solves?
How does the block matrix show that multiplication is no harder than inversion?
- Its determinant is
- Its inverse contains in the top-right block
- It is upper triangular, so it needs no pivoting
- It has the same eigenvalues as