Skip to main content

lib_jsl_linalg_reference/
gaussian_elimination.rs

1//! Gaussian elimination: the algorithm every linear solver descends from.
2//!
3//! To solve `A x = b`, subtract multiples of each row from the rows below it until `A` is upper
4//! triangular, then solve the triangular system from the bottom up (back substitution). The
5//! multiplier for row `i` at step `k` is `a_ik / a_kk`, so everything depends on the **pivot**
6//! `a_kk`. A zero pivot stops the naive algorithm; a tiny one lets rounding errors grow without
7//! bound. **Partial pivoting** swaps the row with the largest `|a_ik|` into the pivot position,
8//! keeping every multiplier at most one in magnitude.
9//!
10//! See the book entry [Gaussian elimination and LU factorisation](https://jwkunz.github.io/lib_jsl/book/linear_algebra/lu.html#gaussian-elimination-and-pivoting).
11
12use crate::Error;
13use ndarray::{Array1, Array2};
14
15/// Solves `A x = b` by elimination **without** pivoting. Fails on a zero pivot and is unstable
16/// when a pivot is small; see [`solve_with_partial_pivoting`].
17pub fn solve_without_pivoting(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
18    let n = a.nrows();
19    let (mut a, mut b) = (a.clone(), b.clone());
20    for k in 0..n {
21        if a[[k, k]] == 0.0 {
22            return Err("zero pivot: elimination without pivoting cannot continue");
23        }
24        for i in k + 1..n {
25            let multiplier = a[[i, k]] / a[[k, k]];
26            for j in k..n {
27                a[[i, j]] -= multiplier * a[[k, j]];
28            }
29            b[i] -= multiplier * b[k];
30        }
31    }
32    back_substitute(&a, &b)
33}
34
35// ANCHOR: partial_pivoting
36/// Solves `A x = b` by elimination with **partial pivoting**: at step `k` the row with the
37/// largest `|a_ik|` (`i ≥ k`) is swapped into the pivot position.
38pub fn solve_with_partial_pivoting(a: &Array2<f64>, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
39    let n = a.nrows();
40    let (mut a, mut b) = (a.clone(), b.clone());
41    for k in 0..n {
42        let pivot_row = (k..n).max_by(|&i, &j| a[[i, k]].abs().total_cmp(&a[[j, k]].abs())).ok_or("empty matrix")?;
43        if a[[pivot_row, k]] == 0.0 {
44            return Err("the matrix is singular");
45        }
46        if pivot_row != k {
47            for j in 0..n {
48                a.swap([k, j], [pivot_row, j]);
49            }
50            b.swap(k, pivot_row);
51        }
52        for i in k + 1..n {
53            let multiplier = a[[i, k]] / a[[k, k]];
54            for j in k..n {
55                a[[i, j]] -= multiplier * a[[k, j]];
56            }
57            b[i] -= multiplier * b[k];
58        }
59    }
60    back_substitute(&a, &b)
61}
62// ANCHOR_END: partial_pivoting
63
64/// Solves the upper triangular system `U x = c`, last unknown first.
65pub fn back_substitute(u: &Array2<f64>, c: &Array1<f64>) -> Result<Array1<f64>, Error> {
66    let n = u.nrows();
67    let mut x = Array1::zeros(n);
68    for i in (0..n).rev() {
69        let sum: f64 = (i + 1..n).map(|j| u[[i, j]] * x[j]).sum();
70        if u[[i, i]] == 0.0 {
71            return Err("zero on the diagonal of the triangular factor");
72        }
73        x[i] = (c[i] - sum) / u[[i, i]];
74    }
75    Ok(x)
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use crate::random_matrix;
82    use ndarray::array;
83
84    #[test]
85    fn both_variants_solve_well_conditioned_systems() {
86        let a = random_matrix(20, 20, 1) + crate::identity(20) * 5.0;
87        let b = Array1::from_iter((0..20).map(|i| i as f64));
88        for x in [solve_without_pivoting(&a, &b).unwrap(), solve_with_partial_pivoting(&a, &b).unwrap()] {
89            assert!((a.dot(&x) - &b).iter().all(|r| r.abs() < 1e-10));
90        }
91    }
92
93    #[test]
94    fn pivoting_rescues_small_pivots() {
95        // The classic example: a tiny pivot ε makes naive elimination lose every digit of x₁.
96        let eps = 1e-17;
97        let a = array![[eps, 1.0], [1.0, 1.0]];
98        let b = array![1.0, 2.0]; // x ≈ (1, 1)
99        let naive = solve_without_pivoting(&a, &b).unwrap();
100        let pivoted = solve_with_partial_pivoting(&a, &b).unwrap();
101        assert!((naive[0] - 1.0).abs() > 0.5, "naive elimination should fail: {naive}");
102        assert!((pivoted[0] - 1.0).abs() < 1e-15 && (pivoted[1] - 1.0).abs() < 1e-15);
103        // A zero pivot stops the naive algorithm outright.
104        assert!(solve_without_pivoting(&array![[0.0, 1.0], [1.0, 0.0]], &array![1.0, 1.0]).is_err());
105        assert!(solve_with_partial_pivoting(&array![[1.0, 2.0], [2.0, 4.0]], &array![1.0, 1.0]).is_err());
106    }
107}