lib_jsl_linalg_reference/
gaussian_elimination.rs1use crate::Error;
13use ndarray::{Array1, Array2};
14
15pub 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
35pub 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}
62pub 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 let eps = 1e-17;
97 let a = array![[eps, 1.0], [1.0, 1.0]];
98 let b = array![1.0, 2.0]; 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 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}