test: solve with gauss jordan

This commit is contained in:
2026-04-29 17:18:35 -06:00
parent 62220c762f
commit dc4d0c8e73

View File

@@ -435,7 +435,7 @@ impl Matrix {
let solved_matrix = solved_matrix.gauss_jordan_elimination()?; let solved_matrix = solved_matrix.gauss_jordan_elimination()?;
let result = solved_matrix let result = solved_matrix
.get_column(solved_matrix.columns)? .get_column(solved_matrix.columns - 1)?
.cloned() .cloned()
.collect(); .collect();
@@ -2850,4 +2850,116 @@ mod tests {
assert!(matches!(res, Err(MatrixError::NotSquared))); assert!(matches!(res, Err(MatrixError::NotSquared)));
} }
#[test]
fn test_solve_simple() {
// 2x + y = 5
// x + y = 3
let m = Matrix {
rows: 2,
columns: 2,
data: vec![
Fraction::from(2),
Fraction::from(1),
Fraction::from(1),
Fraction::from(1),
],
};
let b = vec![Fraction::from(5), Fraction::from(3)];
let res = m.solve_matrix_with_gauss_jordan(b).unwrap();
assert_eq!(res, vec![Fraction::from(2), Fraction::from(1)]);
}
#[test]
fn test_solve_3x3() {
let m = Matrix {
rows: 3,
columns: 3,
data: vec![
Fraction::from(2),
Fraction::from(1),
Fraction::from(-1),
Fraction::from(-3),
Fraction::from(-1),
Fraction::from(2),
Fraction::from(-2),
Fraction::from(1),
Fraction::from(2),
],
};
let b = vec![Fraction::from(8), Fraction::from(-11), Fraction::from(-3)];
let res = m.solve_matrix_with_gauss_jordan(b).unwrap();
assert_eq!(
res,
vec![Fraction::from(2), Fraction::from(3), Fraction::from(-1)]
);
}
#[test]
fn test_solve_identity() {
let m = Matrix {
rows: 2,
columns: 2,
data: vec![
Fraction::from(1),
Fraction::from(0),
Fraction::from(0),
Fraction::from(1),
],
};
let b = vec![Fraction::from(7), Fraction::from(9)];
let res = m.solve_matrix_with_gauss_jordan(b.clone()).unwrap();
assert_eq!(res, b);
}
#[test]
fn test_solve_singular() {
let m = Matrix {
rows: 2,
columns: 2,
data: vec![
Fraction::from(1),
Fraction::from(2),
Fraction::from(2),
Fraction::from(4),
],
};
let b = vec![Fraction::from(3), Fraction::from(6)];
let res = m.solve_matrix_with_gauss_jordan(b);
assert!(matches!(res, Err(MatrixError::FailedGaussJordan)));
}
#[test]
fn test_solve_invalid_size() {
let m = Matrix::new(2, 2, Fraction::from(1)).unwrap();
let b = vec![Fraction::from(1)];
let res = m.solve_matrix_with_gauss_jordan(b);
assert!(matches!(res, Err(MatrixError::InvalidDataSize)));
}
#[test]
fn test_solve_not_squared() {
let m = Matrix::new(2, 3, Fraction::from(1)).unwrap();
let b = vec![Fraction::from(1), Fraction::from(2)];
let res = m.solve_matrix_with_gauss_jordan(b);
assert!(matches!(res, Err(MatrixError::NotSquared)));
}
} }