From dc4d0c8e731053b920f37e1691dd2fb6bc7608a9 Mon Sep 17 00:00:00 2001 From: laentropia Date: Wed, 29 Apr 2026 17:18:35 -0600 Subject: [PATCH] test: solve with gauss jordan --- src/lib.rs | 114 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 113 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index b005e4b..dd98891 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -435,7 +435,7 @@ impl Matrix { let solved_matrix = solved_matrix.gauss_jordan_elimination()?; let result = solved_matrix - .get_column(solved_matrix.columns)? + .get_column(solved_matrix.columns - 1)? .cloned() .collect(); @@ -2850,4 +2850,116 @@ mod tests { 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))); + } }