LU Decomposition and Triangular Solves
Solving a system of linear equations 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 time, as the Gaussian Elimination lesson of the Linear Algebra course shows. The algorithmic view in this lesson reorganizes the elimination as a factorization , 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 is solved from the top down by forward substitution: the first equation involves only , the second only and , and so on:
An upper triangular system is solved from the bottom up by back substitution:
Row costs or operations, so each substitution takes time.
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 xThe factorization
An LU decomposition of writes with unit lower triangular and upper triangular. Then becomes : solve by forward substitution, then by back substitution.
To compute it, split off the first row and column. Write
where and are column vectors of length . Multiply out the right-hand side to check it. The matrix is the Schur complement of . If it has an LU decomposition , then
So the first row of is the first row of , the first column of is divided by the pivot , and the rest is the same problem one size smaller. This is exactly Gaussian elimination: subtracting times row 0 from row is the update . Written iteratively and in place:
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 AThe program factors a integer matrix with exact fractions, prints and and checks .
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 and in hand, each right-hand side costs two triangular solves. The next program solves for two right-hand sides with the factorization computed above, and checks each solution by multiplying back.
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 ; the second gives the first column of , a hint of the next lesson.
Counting the operations
Iteration of LU-DECOMPOSE does divisions and multiply-subtract updates, so the total number of updates is
So the factorization is and each solve is . For right-hand sides, factoring once and solving times costs , instead of for separate eliminations. The program counts exactly.
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 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.
#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 's multipliers below the diagonal and on and above it, which is how LAPACK's getrf returns the factorization too.
When the pivot is zero
Line 3 divides by . If a pivot is zero, the algorithm fails even when is invertible: has no LU decomposition at all, although swapping its rows gives the triangular matrix . 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 (Positive Definite Matrices) does half the work.
Test yourself
How long does forward substitution take for an unit lower triangular system?
In , what is the first column of below the diagonal?
You need to solve for 50 different vectors with the same matrix. What is the best approach?
- Gaussian elimination 50 times
- Factor once, then 50 pairs of triangular solves
- Compute with Cramer's rule
- Strassen's algorithm
Why does have no LU decomposition?
- It is singular
- Its first pivot is 0, and with is impossible
- It is not symmetric
- It is already triangular