matrix with equality

This commit is contained in:
Jon Janzen
2021-03-28 18:00:15 -06:00
parent 2a602f5804
commit f24280c866
2 changed files with 96 additions and 1 deletions

View File

@@ -7,3 +7,4 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
approx = "0.4"

View File

@@ -1,5 +1,9 @@
#[macro_use]
extern crate approx;
use std::ops::Index;
#[derive(Debug)]
pub struct Matrix {
matrix: Vec<Vec<f32>>,
}
@@ -19,12 +23,32 @@ impl Index<usize> for Matrix {
}
}
impl PartialEq for Matrix {
fn eq(&self, _rhs: &Self) -> bool {
if self.matrix.len() != _rhs.matrix.len() {
return false;
}
for row_idx in 0..self.matrix.len() {
if self.matrix[row_idx].len() != _rhs.matrix[row_idx].len() {
return false;
}
for col_idx in 0..self.matrix[row_idx].len() {
if !relative_eq!(self.matrix[row_idx][col_idx], _rhs.matrix[row_idx][col_idx]) {
return false;
}
}
}
return true;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
fn matrix_4x4() {
let m = vec![
vec![1.0, 2.0, 3.0, 4.0],
vec![5.5, 6.5, 7.5, 8.5],
@@ -42,4 +66,74 @@ mod tests {
assert_eq!(15.5, matrix[3][2]);
}
#[test]
fn matrix_2x2() {
let m = vec![
vec![-3.0, 5.0,],
vec![1.0, 2.0,],
];
let matrix = Matrix::new(m);
assert_eq!(-3.0, matrix[0][0]);
assert_eq!(5.0, matrix[0][1]);
assert_eq!(1.0, matrix[1][0]);
assert_eq!(2.0, matrix[1][1]);
}
#[test]
fn matrix_3x3() {
let m = vec![
vec![-3.0, 5.0, 0.0],
vec![1.0, -2.0, -7.0],
vec![0.0, 1.0, 1.0],
];
let matrix = Matrix::new(m);
assert_eq!(-3.0, matrix[0][0]);
assert_eq!(-2.0, matrix[1][1]);
assert_eq!(1.0, matrix[2][2]);
}
#[test]
fn matrix_equality_a() {
let a = vec![
vec![1.0, 2.0, 3.0, 4.0],
vec![5.0, 6.0, 7.0, 8.0],
vec![9.0, 8.0, 7.0, 6.0],
vec![5.0, 4.0, 3.0, 2.0],
];
let m_a = Matrix::new(a);
let b = vec![
vec![1.0, 2.0, 3.0, 4.0],
vec![5.0, 6.0, 7.0, 8.0],
vec![9.0, 8.0, 7.0, 6.0],
vec![5.0, 4.0, 3.0, 2.0],
];
let m_b = Matrix::new(b);
assert_eq!(m_a, m_b);
}
#[test]
fn matrix_equality_b() {
let a = vec![
vec![1.0, 2.0, 3.0, 4.0],
vec![5.0, 6.0, 7.0, 8.0],
vec![9.0, 8.0, 7.0, 6.0],
vec![5.0, 4.0, 3.0, 2.0],
];
let m_a = Matrix::new(a);
let b = vec![
vec![2.0, 3.0, 4.0, 5.0],
vec![6.0, 7.0, 8.0, 9.0],
vec![8.0, 7.0, 6.0, 5.0],
vec![4.0, 3.0, 2.0, 1.0],
];
let m_b = Matrix::new(b);
assert_ne!(m_a, m_b);
}
}