Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Gaussian elimination and LU factorisation

ProblemSolve a square linear system ; factor to solve many systems, compute the determinant, or invert
Devised byElimination: Chinese mathematicians of the Nine Chapters (around 200 BC), Carl Friedrich Gauss (1809); the factorisation: Myrick Doolittle (1878), Prescott Crout (1941), Alan Turing (1948); error analysis: John von Neumann and Herman Goldstine (1947), James Wilkinson (1961); recursive LU: Sivan Toledo (1997)
AccuracyBackward stable in practice with partial pivoting: the computed solution solves a system perturbed by a small multiple of times the growth factor, which is almost always small
Cost flops to factor, per right-hand side, for the inverse
Read firstPreliminaries: norms, Background: stability and conditioning
APISolve, Factorize, LuFactorization, Determinant, Inverse, SolveTriangular; reference: gaussian_elimination, lu

Overview

Gaussian elimination solves by subtracting multiples of each equation from the ones below it until the system is upper triangular, then solving that from the bottom up. It is the oldest algorithm in numerical linear algebra and still the method of choice for dense square systems. Recorded properly, elimination computes a factorisation into a permutation, a unit lower triangular matrix of multipliers and an upper triangular matrix. The factorisation is the useful object: it solves further systems with the same matrix in , and gives the determinant for free.

Two refinements make it work on computers. Partial pivoting, swapping rows to use the largest available pivot, makes it stable. Blocking reorganises the arithmetic around matrix-matrix products, which run near the peak speed of modern processors. The reference crate implements the first, the production crate both.

Where it is used

Gaussian elimination is the workhorse for square systems.

  • Circuit and network analysis. Nodal analysis gives for the node voltages.
  • Structural analysis. Displacements of a truss or frame from its stiffness matrix.
  • Simulation. Implicit time-stepping and Newton’s method solve a linear system at each step.
  • Determinants and inverses. Computed from the same factorisation, and many right-hand sides can reuse it.

History

The Nine Chapters on the Mathematical Art, compiled in China around 200 BC, solve systems of up to five equations by elimination on a counting board, column by column, with the fangcheng rule. Gauss described elimination for the normal equations of least squares in his Theoria motus (1809) and used it in 1810 for the orbit of the asteroid Pallas; his notation made it standard in geodesy and astronomy. Myrick Doolittle of the US Coast and Geodetic Survey (1878) organised the hand calculation as a factorisation, and Prescott Crout (1941) gave the version with a unit upper triangle; Alan Turing (1948) described elimination explicitly as LU factorisation and introduced the condition number.

When computers arrived, John von Neumann and Herman Goldstine (1947) feared that rounding errors would make elimination useless beyond a few dozen equations. James Wilkinson (1961) showed, by backward error analysis, that with partial pivoting it is stable unless the elements grow, and that growth is almost never large in practice, though it can be in contrived examples. The LAPACK project (1992) blocked the algorithm for cache memories, and Sivan Toledo (1997) proposed the recursive formulation that LAPACK adopted as getrf2 and that this library uses.

The idea

Gaussian elimination and pivoting

Elimination by example. Take the system

Subtracting 2 times the first equation from the second, and 4 times the first from the third, removes from both. Then subtracting 3 times the new second equation from the new third removes from it:

The system is now upper triangular, and can be solved from the bottom up: the last equation gives , then the second gives , then the first gives . This last stage is back substitution.

In general. At step , each row is replaced by row minus times row , which zeroes the entries below the diagonal entry , called the pivot. The numbers are the multipliers (2, 4 and 3 in the example). After steps has become an upper triangular matrix and a vector , and back substitution computes for . Elimination costs about arithmetic operations (flops) and back substitution .

Why pivoting is needed. The algorithm divides by the pivot. A zero pivot stops it, even for a perfectly good system (swap the two equations of , and nothing is wrong). A small pivot is more insidious: the algorithm runs, and returns a wrong answer. Consider, with ,

whose solution is very close to . The multiplier is , and the second row becomes . In double precision, with 16 digits, both and round to : the original entries 1 and 2 of the second equation, which distinguished it from any other, have been wiped out. Back substitution gives , correctly, and then , which is completely wrong.

Table 7.2. A small pivot with and without partial pivoting.

without pivoting: with partial pivoting: exact
1.01010101010100551.01010101010100991.0101010101010102
1.00000100000663391.00000100000099981.0000010000010000
1.00000008274037101.00000000010000001.0000000001000000
0.99920072216264091.00000000000001001.0000000000000100
0.00000000000000001.00000000000000001.0000000000000000

Partial pivoting. The damage was done by the huge multiplier. The cure is to swap rows before each step so that the pivot is the largest entry (in magnitude) in its column, on or below the diagonal. Every multiplier then satisfies , and multiples of the pivot row can no longer swamp the rows they are subtracted from. In the example the rows are exchanged, the multiplier is , the second row becomes , and the computed solution is .

How stable is it? The right way to state the accuracy of elimination is due to Wilkinson. The computed solution is not the exact solution of the given system, but it is the exact solution of a nearby system, , with

Here is the machine epsilon, a modest constant, and the entries of the matrix after steps. An algorithm with this property, giving the exact answer to a slightly perturbed problem, is called backward stable, and is the backward error. The bound contains the growth factor , which measures how much larger the entries become during elimination than they were at the start. Pivoting keeps the multipliers small, but entries can still grow, because each step can at most double them. In the worst case . Wilkinson’s example has 1 on the diagonal and in the last column and below the diagonal: partial pivoting never swaps, and the last column doubles at every step.

Table 7.3. Element growth and error on Wilkinson's matrix and random matrices.

growth factor relative error, partial pivotingrelative error, random matrix of the same order
105.1e26.2e-154.3e-15
205.2e51.0e-114.9e-15
305.4e82.9e-85.6e-15
405.5e112.0e-54.1e-14
505.6e145.2e-31.1e-14
605.8e171.5e06.4e-15

Such matrices are almost never met in practice: for random matrices the growth is about , and the error is at the level of rounding, as the last column shows. Complete pivoting, which searches the whole remaining submatrix for the largest entry and swaps columns as well as rows, bounds the growth far better but costs comparisons and is rarely used.

LU factorisation

Elimination does more than solve one system. If the multipliers are kept instead of thrown away, they record everything that was done to . Put them in a lower triangular matrix , with in position and ones on the diagonal (a unit lower triangular matrix). In the example,

as multiplying out confirms. Each row of the product says that a row of is the matching row of plus the multiples of earlier rows that elimination subtracted. With row swaps the statement becomes , where is the permutation matrix that applies all the swaps.

The factorisation separates the expensive part of the work, which depends only on , from the cheap part, which depends on . To solve :

  1. permute the right-hand side, ;
  2. solve from the top down (forward substitution);
  3. solve from the bottom up (back substitution).

This is correct because . The two triangular solves cost flops together, against for the factorisation, so each further right-hand side is almost free.

Two by-products:

  • The determinant is the product of the pivots, , with a minus sign if the number of row swaps is odd. In the example, .
  • The inverse can be found by solving for each column of the identity. It costs flops, three times the factorisation, and is rarely needed: to compute , solving the system is both more accurate and cheaper than forming the inverse and multiplying.

Conditioning

Backward stability says that the computed solution exactly solves a nearby problem. It does not say that the solution is close to the true one. That depends on how sensitive the solution is to small changes in the data, which is a property of the matrix, not of the algorithm. It is measured by the condition number

and the rule is

With a backward error near , a matrix with loses about six of the sixteen digits. The notoriously ill-conditioned Hilbert matrices show both halves of the statement: the error grows exactly as , while the backward error stays at the level of rounding.

Figure 7.1. Hilbert systems.

Beyond order 13, exceeds : the computed inverse used to estimate it is itself meaningless, and the “solution” has no correct digits, although it still satisfies the system to rounding accuracy. A small residual is therefore not evidence of an accurate solution.

Blocked and recursive factorisation

The textbook algorithm performs flops as updates of single rows, each reading and writing memory: on modern processors it runs at the speed of memory, not of arithmetic. Reorganising the same operations into multiplications of blocks lets each number fetched from memory be used many times. Recursive LU splits the columns in half:

  1. factor the left half recursively, with pivoting;
  2. solve for the top right block;
  3. update the bottom right block, , with one matrix multiplication;
  4. factor the updated recursively.

Nearly all the arithmetic is in step 3, at every level of the recursion, so the factorisation runs at close to the speed of the matrix-multiply kernel. The library factors narrow panels (32 columns) in column-major order, where the pivot searches run along contiguous memory, and solves triangular systems in blocks the same way:

Figure 7.2. Factorisation speed.

On this laptop the reference Doolittle LU stays near 2 GFLOP/s, limited by memory; the recursive LU reaches about 20 GFLOP/s at , and LAPACK with OpenBLAS is 1.1 to 1.6 times faster still.

Algorithm

Gaussian elimination with partial pivoting (the reference crate). Input: an matrix and a right-hand side . For :

  1. Pivot search. Find the row with the largest . If that entry is zero, the matrix is singular.
  2. Swap rows and of , and the same entries of .
  3. Eliminate. For each row , compute the multiplier and subtract times row from row , and from . Only the columns to the right of need updating, since the entries below the pivot are known to become zero.

Then back substitute: for down to 1, .

To obtain the factorisation instead of a single solution, store each multiplier in the position it has just zeroed, and record the swaps. At the end the array holds on and above the diagonal and (without its unit diagonal) below it.

Recursive LU (the production crate) performs the same arithmetic in a different order.

  1. Split the matrix into panels of at most 32 columns.
  2. Factor the current panel with partial pivoting, by the recursion on halves of its columns described above, working in column-major order.
  3. Apply the panel’s row swaps to the rest of the matrix.
  4. Solve a triangular system for the block of to the right of the panel.
  5. Update the trailing submatrix with one matrix multiplication, and continue with the next panel.

A pivot smaller than is reported as a singular matrix. Both versions cost flops.

Implementation

The textbook algorithm:

/// Solves `A x = b` by elimination with **partial pivoting**: at step `k` the row with the
/// largest `|a_ik|` (`i ≥ k`) is swapped into the pivot position.
pub fn solve_with_partial_pivoting(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
    let n = a.nrows();
    let (mut a, mut b) = (a.clone(), b.clone());
    for k in 0..n {
        let pivot_row = (k..n).max_by(|&i, &j| a[[i, k]].abs().total_cmp(&a[[j, k]].abs())).ok_or("empty matrix")?;
        if a[[pivot_row, k]] == 0.0 {
            return Err("the matrix is singular");
        }
        if pivot_row != k {
            for j in 0..n {
                a.swap([k, j], [pivot_row, j]);
            }
            b.swap(k, pivot_row);
        }
        for i in k + 1..n {
            let multiplier = a[[i, k]] / a[[k, k]];
            for j in k..n {
                a[[i, j]] -= multiplier * a[[k, j]];
            }
            b[i] -= multiplier * b[k];
        }
    }
    back_substitute(&a, &b)
}

Doolittle LU, keeping the multipliers:

/// Factorises a square matrix with partial pivoting.
pub fn lu(a: &Array2<f64>) -> Result<Lu, Error> {
    let n = a.nrows();
    let mut u = a.clone();
    let mut l = crate::identity(n);
    let mut rows: Vec<usize> = (0..n).collect();
    let mut swaps = 0;
    for k in 0..n {
        let p = (k..n).max_by(|&i, &j| u[[i, k]].abs().total_cmp(&u[[j, k]].abs())).ok_or("empty matrix")?;
        if u[[p, k]] == 0.0 {
            return Err("the matrix is singular");
        }
        if p != k {
            for j in 0..n {
                u.swap([k, j], [p, j]);
            }
            // Multipliers already computed move with their rows.
            for j in 0..k {
                l.swap([k, j], [p, j]);
            }
            rows.swap(k, p);
            swaps += 1;
        }
        for i in k + 1..n {
            l[[i, k]] = u[[i, k]] / u[[k, k]];
            for j in k..n {
                u[[i, j]] -= l[[i, k]] * u[[k, j]];
            }
        }
    }
    Ok(Lu { l, u, rows, swaps })
}

The production recursion:

/// Factorises the panel of columns `k..k + w` (rows `k..n`) of the square buffer in place,
/// swapping whole rows so that every column sees the same permutation.
fn recursive_lu<T: Scalar>(a: &mut Mat<T>, pivots: &mut [usize], k: usize, w: usize, threshold: f64) -> Result<()> {
    let n = a.cols;
    if w <= LEAF {
        return unblocked_panel(a, pivots, k, w, threshold);
    }
    let w1 = w / 2;
    recursive_lu(a, pivots, k, w1, threshold)?;
    // A₁₂ ← L₁₁⁻¹ A₁₂ (rows k..k+w1, columns k+w1..k+w).
    unit_lower_solve(a, k, w1, k + w1, w - w1);
    // A₂₂ ← A₂₂ − A₂₁ A₁₂ (rows k+w1..n, columns k+w1..k+w).
    let ptr = a.data.as_mut_ptr();
    // SAFETY: A₂₁ (columns k..k+w1, rows ≥ k+w1), A₁₂ (rows k..k+w1) and A₂₂ are disjoint.
    unsafe { sub_matmul(n - k - w1, w1, w - w1, ptr.add((k + w1) * n + k), n, ptr.add(k * n + k + w1), n, ptr.add((k + w1) * n + k + w1), n) };
    recursive_lu(a, pivots, k + w1, w - w1, threshold)
}
  • All production routines work for f64 and Complex<f64> through the Scalar trait.
  • solve factorises and solves; factorize returns an LuFactorization to reuse; solve_t and solve_h solve with and .
  • The inverse is computed as , using the triangularity of to save a third of the work, as LAPACK’s getri does. Both triangular solves are recursive on halves of the rows (since 2.33): the first half is solved, its contribution to the second half is one large matrix product, and only triangles of order 16 are done row by row. That took the inverse at from 1.7 to 1.2 times LAPACK’s time.

In practice

//! Solving linear systems: textbook Gaussian elimination and production LU.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_lu`.

use lib_jsl_linalg::{Determinant, Factorize, Inverse, Solve};
use lib_jsl_linalg_reference::{gaussian_elimination, lu};
use ndarray::{Array1, array};

fn main() {
    // Currents in a three-loop resistor network (Kirchhoff's laws).
    let a = array![[10.0, -2.0, -3.0], [-2.0, 12.0, -4.0], [-3.0, -4.0, 15.0]];
    let b = array![12.0, 0.0, 6.0];

    // The textbook algorithm, from the reference crate.
    let x_ref = gaussian_elimination::solve_with_partial_pivoting(&a, &b).unwrap();
    println!("reference elimination: {x_ref:.6}");

    // The production solver: LU with partial pivoting, for real or complex matrices.
    let x = a.solve(&b).unwrap();
    println!("production solve:      {x:.6}");

    // Factor once, then solve for many right-hand sides at O(n²) each.
    let f = a.factorize().unwrap();
    for rhs in [array![1.0, 0.0, 0.0], array![0.0, 1.0, 0.0]] {
        println!("A x = {rhs}: x = {:.6}", f.solve(&rhs).unwrap());
    }
    println!("det A = {:.6} (reference {:.6})", a.det().unwrap(), lu::lu(&a).unwrap().determinant());
    let check = a.dot(&a.inv().unwrap());
    println!("max |A A⁻¹ − I| = {:.1e}", (&check - &ndarray::Array2::<f64>::eye(3)).iter().fold(0.0f64, |m, v| m.max(v.abs())));

    // A singular matrix is reported, not divided by zero.
    println!("singular: {:?}", array![[1.0, 2.0], [2.0, 4.0]].solve(&Array1::from(vec![1.0, 1.0])));
}

Strengths

  • The general-purpose dense solver: stable in practice, flops, near peak speed when blocked.
  • The factorisation is reusable, and gives determinants.

Weaknesses

  • Not guaranteed stable: exponential growth is possible, though almost never met.
  • Dense storage and cost: large sparse systems need sparse or iterative methods.
  • Ignores structure: use Cholesky for symmetric positive definite matrices, at half the cost.

Exercises

  1. Count the flops of Gaussian elimination and show that the leading term is .
  2. Show that the inverse of a unit lower triangular matrix is unit lower triangular, and that the multipliers of elimination are the entries of .
  3. Prove that partial pivoting gives growth factor at most , and that Wilkinson’s matrix attains it.
  4. Solve for the Hilbert matrix of order 10 with , perturb one entry of by , and compare the change in with .
  5. Use the factorisation to compute for a random matrix scaled by 10. Why can the determinant overflow even when the matrix is well conditioned, and how would you compute instead?
Hints and answers
  1. Step updates an block with one multiplication and one subtraction per entry: .
  2. A unit lower triangular matrix has an inverse of the same form (back substitution on the identity gives ones on the diagonal and zeros above). Elimination subtracts times row from row , and those are the entries of .
  3. With partial pivoting , so each step at most doubles the largest entry: after steps at most . Wilkinson’s matrix (ones on the diagonal and in the last column, below the diagonal) doubles the last column at every step.
  4. . A perturbation of in one entry of can change by a relative amount up to about (relative perturbation), potentially of order ; the actual change depends on the direction of the perturbation.
  5. Scaling a matrix by 10 multiplies its determinant by . For a matrix of standard normal entries is typically near , so the result is around , beyond the largest double (). Compute instead.

Further reading

  • G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins University Press, 2013, chapter 3.
  • N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, chapter 9.
  • L. N. Trefethen and D. Bau, Numerical Linear Algebra, SIAM, 1997, lectures 20–23.
  • S. Toledo, “Locality of reference in LU decomposition with partial pivoting”, SIAM Journal on Matrix Analysis and Applications 18 (1997) 1065–1081.
  • J. F. Grcar, “Mathematicians of Gaussian elimination”, Notices of the American Mathematical Society 58 (2011) 782–792.