TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › LUP Decomposition, Solving and Inverting

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 kk, swap the row with the largest entry in that column into the pivot position. Recording the swaps as a permutation gives the LUP decomposition PA=LUPA = LU, 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

(10−20111)(x0x1)=(12),\begin{pmatrix} 10^{-20} & 1 \\ 1 & 1 \end{pmatrix} \begin{pmatrix} x_0 \\ x_1 \end{pmatrix} = \begin{pmatrix} 1 \\ 2 \end{pmatrix},

whose solution is extremely close to x0=x1=1x_0 = x_1 = 1. LU without exchanges uses the pivot 10−2010^{-20}, the multiplier l10=1020l_{10} = 10^{20}, and computes u11=1−1020u_{11} = 1 - 10^{20}, which rounds to −1020-10^{20}: the information in the entry 1 is lost. Swapping the rows first makes the multiplier 10−2010^{-20} and nothing is lost.

python · try it yourself
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 x0x_0 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 2n2^n, but they essentially never occur).

The factorization PA=LUPA = LU

A permutation matrix PP has exactly one 1 in every row and column; PAPA reorders the rows of AA. Store it compactly as an array π\pi: row ii of PAPA is row π[i]\pi[i] of AA. The algorithm is LU-DECOMPOSE with a row exchange in front of each elimination step:

text
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 pi

Swapping whole rows, including the multipliers already stored in the columns left of kk, keeps LL consistent with the permutation. If column kk has no nonzero entry from row kk down, the first k+1k + 1 columns of the current matrix are linearly dependent and AA is singular. So for an invertible AA the algorithm always succeeds: every invertible matrix has an LUP decomposition. The extra cost is Θ(n2)\Theta(n^2) comparisons in total, nothing against the Θ(n3)\Theta(n^3) updates.

To solve Ax=bAx = b: since PA=LUPA = LU, the system is LUx=PbLUx = Pb. Permute bb (the vector PbPb has entries b[π[i]]b[\pi[i]]), then do forward and back substitution as before. As a bonus, det⁡A=(−1)s∏iuii\det A = (-1)^s \prod_i u_{ii}, where ss is the number of actual swaps.

python · try it yourself
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 X=A−1X = A^{-1} satisfies AX=IAX = I, which is nn separate systems Axj=ejAx_j = e_j, one per column of the identity. With one LUP decomposition (Θ(n3)\Theta(n^3)) and nn solves (Θ(n2)\Theta(n^2) each), inversion takes Θ(n3)\Theta(n^3) time in total. In practice you rarely need A−1A^{-1} itself: to compute A−1bA^{-1}b, solving Ax=bAx = b is both faster and more accurate.

python · try it yourself
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 n×nn \times n matrices AA and BB, the 3n×3n3n \times 3n block matrix below is always invertible, and its inverse contains the product:

(IA00IB00I)−1=(I−AAB0I−B00I).\begin{pmatrix} I & A & 0 \\ 0 & I & B \\ 0 & 0 & I \end{pmatrix}^{-1} = \begin{pmatrix} I & -A & AB \\ 0 & I & -B \\ 0 & 0 & I \end{pmatrix}.

Multiplying the two matrices gives the identity, which proves the formula. So an algorithm that inverts 3n×3n3n \times 3n matrices in time I(3n)I(3n) multiplies n×nn \times n matrices in time I(3n)+O(n2)I(3n) + O(n^2).

Inversion reduces to multiplication. Conversely, a divide-and-conquer inversion through Schur complements (for symmetric positive-definite matrices, and for any invertible AA by inverting ATAA^TA and multiplying by ATA^T) inverts in O(M(n))O(M(n)) time, where M(n)M(n) is the time to multiply, provided MM grows at least like n2n^2 and is reasonably regular. With Strassen's algorithm, matrices can be inverted in O(nlg⁡7)O(n^{\lg 7}) time.

The program checks the block identity on a small example.

python · try it yourself
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 4×44 \times 4 system whose first pivot position would be fine but whose second is zero without exchanges.

cpp · try it yourself
#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 kk?

  1. Row kk, always
  2. The row i≥ki \ge k with the largest ∣aik∣\lvert a_{ik} \rvert
  3. The row with the smallest nonzero entry in column kk
  4. A random row

With PA=LUPA = LU, how do you solve Ax=bAx = b?

  1. Solve Ly=bLy = b, then Ux=yUx = y, then permute xx
  2. Solve Ly=PbLy = Pb by forward substitution, then Ux=yUx = y by back substitution
  3. Solve Ux=PbUx = Pb only
  4. Compute A−1A^{-1} first

What is the running time of inverting an n×nn \times n matrix with one LUP decomposition and nn solves?

  1. Θ(n2)\Theta(n^2)
  2. Θ(n3)\Theta(n^3)
  3. Θ(n4)\Theta(n^4)
  4. Θ(n3lg⁡n)\Theta(n^3 \lg n)

How does the 3n×3n3n \times 3n block matrix show that multiplication is no harder than inversion?

  1. Its determinant is det⁡(AB)\det(AB)
  2. Its inverse contains ABAB in the top-right block
  3. It is upper triangular, so it needs no pivoting
  4. It has the same eigenvalues as ABAB