Implement 2x2 determinant

This commit is contained in:
Bill Thiede 2021-07-01 20:54:00 -07:00
parent dda29eb836
commit c97bc25323

View File

@ -18,6 +18,22 @@ impl Matrix2x2 {
pub fn new(r0: [f32; 2], r1: [f32; 2]) -> Matrix2x2 {
Matrix2x2 { m: [r0, r1] }
}
/// Calculate the determinant of a 2x2.
///
/// # Examples
///
/// ```
/// use rtchallenge::matrices::Matrix2x2;
///
/// let a = Matrix2x2::new([1., 5.], [-3., 2.]);
///
/// assert_eq!(a.determinant(), 17.);
/// ```
pub fn determinant(&self) -> f32 {
let m = self;
m[(0, 0)] * m[(1, 1)] - m[(0, 1)] * m[(1, 0)]
}
}
impl Index<(usize, usize)> for Matrix2x2 {
type Output = f32;
@ -131,7 +147,7 @@ impl Matrix4x4 {
/// use rtchallenge::matrices::Matrix4x4;
///
/// let i = Matrix4x4::identity();
/// assert_eq!(i.inverse() * i, i);
/// assert_eq!(i.inverse_old() * i, i);
///
/// let m = Matrix4x4::new(
/// [2., 0., 0., 0.],
@ -139,10 +155,10 @@ impl Matrix4x4 {
/// [0., 0., 4., 0.],
/// [0., 0., 0., 1.],
/// );
/// assert_eq!(m.inverse() * m, i);
/// assert_eq!(m * m.inverse(), i);
/// assert_eq!(m.inverse_old() * m, i);
/// assert_eq!(m * m.inverse_old(), i);
/// ```
pub fn inverse(&self) -> Matrix4x4 {
pub fn inverse_old(&self) -> Matrix4x4 {
// TODO(wathiede): how come the C++ version doesn't need to deal with non-invertable
// matrix.
let mut indxc: [usize; 4] = Default::default();