~samhsmith/quatmaths

34ba538fc1d49618752b57efbd55edf3ea3f8660 — Sam H. Smith 2 years ago 3a1ae31
added quaternion division
1 files changed, 16 insertions(+), 2 deletions(-)

M src/lib.rs
M src/lib.rs => src/lib.rs +16 -2
@@ 79,12 79,17 @@ impl<T> Quaternion<T> where T : Float
        self.z = -self.z;
        self
    }
    pub fn inverse(mut self) -> Self
    pub fn inverse(self) -> Self
    {
        // the inverse is equal to the conjugate divided by the conjugate multiplied by the original   q' = q*/(q* x q)
        let mut divide_by = Quaternion::mul(self, self.conj()).w;
        let divide_by = Quaternion::mul(self, self.conj()).w;
        Quaternion::div_scalar(self.conj(), divide_by)
    }
    pub fn div(a : Quaternion<T>, b : Quaternion<T>) -> Self
    {
        // quaternion division is the same as multiplying by the inverse
        Quaternion::mul(a, b.inverse())
    }
}

#[cfg(test)]


@@ 127,4 132,13 @@ mod tests {
            Quaternion::<f64>::mul(Quaternion::mul(Quaternion::new(4.0,3.0,2.0,1.0), Quaternion::new(1.0,2.0,3.0,4.0)), Quaternion::new(1.0,2.0,3.0,4.0).inverse()),
            Quaternion::<f64>::new(4.0,3.0,2.0,1.0), 0.01));
    }

    #[test]
    fn test_quaternion_division()
    {
        // multiplying with a quaternion and then it's inverse should result in no change save for floating point errors
        assert!(Quaternion::<f32>::approx_equal(
            Quaternion::div(Quaternion::mul(Quaternion::new(4.0,3.0,2.0,1.0), Quaternion::new(1.0,2.0,3.0,4.0)), Quaternion::new(1.0,2.0,3.0,4.0)),
            Quaternion::new(4.0,3.0,2.0,1.0), 0.01));
    }
}