TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › LU Decomposition and Triangular Solves

LU Decomposition and Triangular Solves

Solving a system of linear equations Ax=bAx = b is the most common task in numerical computing: circuit simulation, structural analysis, least squares fits and the inner loop of many optimization methods all reduce to it. Gaussian elimination solves it in Θ(n3)\Theta(n^3) time, as the Gaussian Elimination lesson of the Linear Algebra course shows. The algorithmic view in this lesson reorganizes the elimination as a factorization A=LUA = LU, which separates the expensive part, done once, from the cheap part, done for every right-hand side.

Triangular systems are easy

A matrix is lower triangular if all entries above the diagonal are zero, and unit lower triangular if moreover its diagonal entries are 1. A lower triangular system Ly=bLy = b is solved from the top down by forward substitution: the first equation involves only y0y_0, the second only y0y_0 and y1y_1, and so on:

yi=bi−∑j=0i−1lij yj(i=0,1,…,n−1, with lii=1).y_i = b_i - \sum_{j=0}^{i-1} l_{ij}\, y_j \qquad (i = 0, 1, \ldots, n - 1,\ \text{with } l_{ii} = 1).

An upper triangular system Ux=yUx = y is solved from the bottom up by back substitution:

xi=1uii(yi−∑j=i+1n−1uij xj)(i=n−1,…,0).x_i = \frac{1}{u_{ii}} \Bigl( y_i - \sum_{j=i+1}^{n-1} u_{ij}\, x_j \Bigr) \qquad (i = n - 1, \ldots, 0).

Row ii costs Θ(i)\Theta(i) or Θ(n−i)\Theta(n - i) operations, so each substitution takes Θ(n2)\Theta(n^2) time.

text
FORWARD-SUB(L, b, n)              BACK-SUB(U, y, n)
1  for i = 0 to n - 1             1  for i = n - 1 downto 0
2      y[i] = b[i]                2      x[i] = y[i]
3      for j = 0 to i - 1         3      for j = i + 1 to n - 1
4          y[i] -= L[i][j] * y[j] 4          x[i] -= U[i][j] * x[j]
5  return y                       5      x[i] = x[i] / U[i][i]
                                  6  return x

The factorization

An LU decomposition of AA writes A=LUA = LU with LL unit lower triangular and UU upper triangular. Then Ax=bAx = b becomes L(Ux)=bL(Ux) = b: solve Ly=bLy = b by forward substitution, then Ux=yUx = y by back substitution.

To compute it, split off the first row and column. Write

A=(a00wTvA′)=(10v/a00I)(a00wT0A′−vwT/a00),A = \begin{pmatrix} a_{00} & w^T \\ v & A' \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ v / a_{00} & I \end{pmatrix} \begin{pmatrix} a_{00} & w^T \\ 0 & A' - v w^T / a_{00} \end{pmatrix},

where vv and ww are column vectors of length n−1n - 1. Multiply out the right-hand side to check it. The matrix A′−vwT/a00A' - v w^T / a_{00} is the Schur complement of a00a_{00}. If it has an LU decomposition L′U′L'U', then

A=(10v/a00L′)(a00wT0U′).A = \begin{pmatrix} 1 & 0 \\ v / a_{00} & L' \end{pmatrix} \begin{pmatrix} a_{00} & w^T \\ 0 & U' \end{pmatrix}.

So the first row of UU is the first row of AA, the first column of LL is vv divided by the pivot a00a_{00}, and the rest is the same problem one size smaller. This is exactly Gaussian elimination: subtracting li0l_{i0} times row 0 from row ii is the update A′−vwT/a00A' - v w^T / a_{00}. Written iteratively and in place:

text
LU-DECOMPOSE(A, n)                 // overwrites A: U on and above the diagonal, L below
1  for k = 0 to n - 1
2      for i = k + 1 to n - 1
3          A[i][k] = A[i][k] / A[k][k]          // l_ik; fails if A[k][k] == 0
4      for i = k + 1 to n - 1
5          for j = k + 1 to n - 1
6              A[i][j] = A[i][j] - A[i][k] * A[k][j]
7  return A

The program factors a 4×44 \times 4 integer matrix with exact fractions, prints LL and UU and checks LU=ALU = A.

python · try it yourself
from fractions import Fraction

def lu_decompose(A):
    n = len(A)
    a = [[Fraction(x) for x in row] for row in A]
    for k in range(n):
        if a[k][k] == 0:
            raise ZeroDivisionError(f"zero pivot in column {k}")
        for i in range(k + 1, n):
            a[i][k] /= a[k][k]
        for i in range(k + 1, n):
            for j in range(k + 1, n):
                a[i][j] -= a[i][k] * a[k][j]
    L = [[a[i][j] if j < i else Fraction(int(i == j)) for j in range(n)] for i in range(n)]
    U = [[a[i][j] if j >= i else Fraction(0) for j in range(n)] for i in range(n)]
    return L, U

def show(name, M):
    print(name)
    for row in M:
        print("  " + " ".join(f"{str(x):>4}" for x in row))

A = [[2, 1, -1, 3], [4, 5, 0, 7], [-2, 8, 11, -2], [6, -3, 1, 8]]
L, U = lu_decompose(A)
show("L =", L)
show("U =", U)
LU = [[sum(L[i][k] * U[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
print("LU == A:", LU == A)
L =
     1    0    0    0
     2    1    0    0
    -1    3    1    0
     3   -2    2    1
U =
     2    1   -1    3
     0    3    2    1
     0    0    4   -2
     0    0    0    5
LU == A: True

Solving, once factored

With LL and UU in hand, each right-hand side costs two triangular solves. The next program solves Ax=bAx = b for two right-hand sides with the factorization computed above, and checks each solution by multiplying back.

python · try it yourself
from fractions import Fraction

def lu_decompose(A):
    n = len(A)
    a = [[Fraction(x) for x in row] for row in A]
    for k in range(n):
        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                                    # L below the diagonal, U on and above

def forward_sub(a, b):
    y = []
    for i in range(len(b)):
        y.append(b[i] - sum(a[i][j] * y[j] for j in range(i)))
    return y

def back_sub(a, y):
    n = len(y)
    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 = [[2, 1, -1, 3], [4, 5, 0, 7], [-2, 8, 11, -2], [6, -3, 1, 8]]
packed = lu_decompose(A)
for b in ([3, 8, 11, 31], [1, 0, 0, 0]):
    y = forward_sub(packed, b)
    x = back_sub(packed, y)
    check = [sum(A[i][j] * x[j] for j in range(4)) for i in range(4)]
    print("b =", b, " y =", [str(v) for v in y], " x =", [str(v) for v in x], " Ax == b:", check == b)
b = [3, 8, 11, 31]  y = ['3', '2', '8', '10']  x = ['1', '-2', '3', '2']  Ax == b: True
b = [1, 0, 0, 0]  y = ['1', '-2', '7', '-21']  x = ['737/120', '29/30', '-7/20', '-21/5']  Ax == b: True

The first right-hand side has the integer solution x=(1,−2,3,2)x = (1, -2, 3, 2); the second gives the first column of A−1A^{-1}, a hint of the next lesson.

Counting the operations

Iteration kk of LU-DECOMPOSE does n−k−1n - k - 1 divisions and (n−k−1)2(n - k - 1)^2 multiply-subtract updates, so the total number of updates is

∑k=0n−1(n−k−1)2=∑m=0n−1m2=(n−1)n(2n−1)6≈n33.\sum_{k=0}^{n-1} (n - k - 1)^2 = \sum_{m=0}^{n-1} m^2 = \frac{(n-1)n(2n-1)}{6} \approx \frac{n^3}{3}.

So the factorization is Θ(n3)\Theta(n^3) and each solve is Θ(n2)\Theta(n^2). For kk right-hand sides, factoring once and solving kk times costs Θ(n3+kn2)\Theta(n^3 + kn^2), instead of Θ(kn3)\Theta(kn^3) for kk separate eliminations. The program counts exactly.

python · try it yourself
def count_lu(n):
    divs = updates = 0
    for k in range(n):
        divs += n - k - 1
        updates += (n - k - 1) ** 2
    return divs, updates

def count_solve(n):
    return sum(range(n)) + sum(range(n)) + n       # forward + back multiply-adds, n divisions

print("    n    LU updates   (n-1)n(2n-1)/6   n^3/3        one solve")
for n in [4, 10, 100, 1000]:
    d, u = count_lu(n)
    print(f"{n:5} {u:13} {(n - 1) * n * (2 * n - 1) // 6:16} {n ** 3 / 3:12.0f} {count_solve(n):12}")
    n    LU updates   (n-1)n(2n-1)/6   n^3/3        one solve
    4            14               14           21           16
   10           285              285          333          100
  100        328350           328350       333333        10000
 1000     332833500        332833500    333333333      1000000

For n=1000n = 1000 the factorization costs about 333 million updates and each later solve about a million: three hundred times cheaper.

In C++

The in-place factorization and the two substitutions in C++, in double arithmetic. The matrix has integer factors, so the printed results are exact.

cpp · try it yourself
#include <cstdio>
#include <vector>
using Matrix = std::vector<std::vector<double>>;

void lu_decompose(Matrix& a) {
    int n = int(a.size());
    for (int k = 0; k < n; k++)
        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];
        }
}

std::vector<double> solve(const Matrix& a, std::vector<double> b) {
    int n = int(a.size());
    for (int i = 0; i < n; i++)                         // forward: L y = b
        for (int j = 0; j < i; j++) b[i] -= a[i][j] * b[j];
    for (int i = n - 1; i >= 0; i--) {                  // back: U x = y
        for (int j = i + 1; j < n; j++) b[i] -= a[i][j] * b[j];
        b[i] /= a[i][i];
    }
    return b;
}

int main() {
    Matrix a = {{2, 1, -1, 3}, {4, 5, 0, 7}, {-2, 8, 11, -2}, {6, -3, 1, 8}};
    lu_decompose(a);
    std::printf("packed L\\U:\n");
    for (auto& row : a) {
        for (double x : row) std::printf("%6.1f", x);
        std::printf("\n");
    }
    auto x = solve(a, {3, 8, 11, 31});
    std::printf("x = %.1f %.1f %.1f %.1f\n", x[0], x[1], x[2], x[3]);
}
packed L\U:
   2.0   1.0  -1.0   3.0
   2.0   3.0   2.0   1.0
  -1.0   3.0   4.0  -2.0
   3.0  -2.0   2.0   5.0
x = 1.0 -2.0 3.0 2.0

The packed matrix holds LL's multipliers below the diagonal and UU on and above it, which is how LAPACK's getrf returns the factorization too.

When the pivot is zero

Line 3 divides by A[k][k]A[k][k]. If a pivot is zero, the algorithm fails even when AA is invertible: (0111)\begin{pmatrix} 0 & 1 \\ 1 & 1 \end{pmatrix} has no LU decomposition at all, although swapping its rows gives the triangular matrix (1101)\begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}. Tiny pivots are almost as bad in floating point, because dividing by them amplifies rounding errors. Both problems are cured by exchanging rows, the subject of LUP Decomposition, Solving and Inverting. For symmetric positive-definite matrices no exchanges are ever needed, and the related Cholesky factorization A=LLTA = LL^T (Positive Definite Matrices) does half the work.

Test yourself

How long does forward substitution take for an n×nn \times n unit lower triangular system?

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

In A=(a00wTvA′)A = \begin{pmatrix} a_{00} & w^T \\ v & A' \end{pmatrix}, what is the first column of LL below the diagonal?

  1. vv
  2. v/a00v / a_{00}
  3. w/a00w / a_{00}
  4. A′−vwTA' - vw^T

You need to solve Ax=bAx = b for 50 different vectors bb with the same 1000×10001000 \times 1000 matrix. What is the best approach?

  1. Gaussian elimination 50 times
  2. Factor A=LUA = LU once, then 50 pairs of triangular solves
  3. Compute A−1A^{-1} with Cramer's rule
  4. Strassen's algorithm

Why does (0111)\begin{pmatrix} 0 & 1 \\ 1 & 1 \end{pmatrix} have no LU decomposition?

  1. It is singular
  2. Its first pivot is 0, and l10u00=1l_{10} u_{00} = 1 with u00=a00=0u_{00} = a_{00} = 0 is impossible
  3. It is not symmetric
  4. It is already triangular