fix: fixed incorrect determinant sum

This commit is contained in:
Zhongheng Liu 2025-01-22 12:58:56 +02:00
commit 6357661920
Signed by: steven
GPG key ID: 805A28B071DAD84B

View file

@ -57,25 +57,34 @@ impl Matrix {
pub fn splice(&self, at_index: usize) -> Matrix { pub fn splice(&self, at_index: usize) -> Matrix {
let mut data: Vec<Vec<i32>> = Vec::new(); let mut data: Vec<Vec<i32>> = Vec::new();
for i in 0..self.data.len() { for i in 0..self.data.len() {
if i == at_index {continue;} if i == 0 {
let mut r: Vec<i32> = Vec::new(); continue;
}
let mut r: Vec<i32> = Vec::new();
for j in 0..self.data[i].len() { for j in 0..self.data[i].len() {
if j == at_index {continue;} if j == at_index {
continue;
}
r.push(self.data[i][j]); r.push(self.data[i][j]);
} }
data.push(r); data.push(r);
} }
Matrix::new(data) let m = Matrix::new(data);
// println!("Splice at {}: {}", at_index, m);
m
} }
pub fn determinant(&self) -> i32 { pub fn determinant(&self) -> i32 {
if !self.is_square() { panic!() };
if self.nrows == 2 && self.nrows == 2 { if self.nrows == 2 && self.nrows == 2 {
return &self.data[0][0] * &self.data[0][1] - &self.data[1][0] * &self.data[1][1]; return &self.data[0][0] * &self.data[1][1] - &self.data[0][1] * &self.data[1][0];
} }
let mut tmp = 0; let mut tmp = 0;
for (i, n) in self.data[0].iter().enumerate() { for (i, n) in self.data[0].iter().enumerate() {
let mult = if i % 2 == 0 { -*n } else { *n }; let mult = if i % 2 == 0 { -*n } else { *n };
let eval = self.splice(i).determinant(); let eval = self.splice(i).determinant();
// println!("tmp result: {}", mult * eval);
tmp += mult * eval; tmp += mult * eval;
// println!("tmp: {}", tmp);
} }
tmp tmp
} }