From 4e55f98cac43a71f6a83aa9d81b1cb26c1745e55 Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Fri, 2 Dec 2016 05:14:21 +0200 Subject: Added division --- src/complex.rs | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/src/complex.rs b/src/complex.rs index 960dba4..93495fa 100644 --- a/src/complex.rs +++ b/src/complex.rs @@ -1,4 +1,4 @@ -use std::ops::{Add, Sub, Mul, Neg}; +use std::ops::{Add, Sub, Mul, Div, Neg}; use ::num_traits::{Trig, Pow}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -25,11 +25,22 @@ impl Complex where T: Trig + Mul + Copy { Complex::new(real, imag) } } + +impl Complex where T: Pow + Add + Copy { + pub fn magnitude(self) -> T { + (self.real.pow(2) + self.imag.pow(2)).sqrt() + } +} + +impl Complex where T: Trig + Copy { + pub fn angle(self) -> T { + self.imag.atan2(self.real) + } +} + impl Complex where T: Trig + Pow + Add + Copy { pub fn to_polar(self) -> (T, T) { - let r = (self.real.pow(2) + self.imag.pow(2)).sqrt(); - let theta = self.imag.atan2(self.real); - (r, theta) + (self.magnitude(), self.angle()) } } @@ -63,6 +74,22 @@ impl Mul for Complex where T: Add + Mul + Sub Div for Complex where T: Add + Mul + Sub + Div + Neg + Copy { + type Output = Complex; + + fn div(self, other: Self) -> Self { + // multiply numerator and denominator by denominator's complex + // conjugate, to give a pure real denominator. + let other_conj = other.conjugate(); + let num = self * other_conj; + let denom = (other * other_conj).real; + + let real = num.real / denom; + let imag = num.imag / denom; + Complex::new(real, imag) + } +} + #[cfg(test)] mod tests { use super::*; @@ -89,6 +116,12 @@ mod tests { assert_eq!(a*b, Complex::new(-6, 17)); } + #[test] + fn division() { + let a = Complex::new(6, 8); + let b = Complex::new(3, 4); + assert_eq!(a/b, Complex::new(2, 0)); + } #[test] fn from_polar() { -- cgit v1.2.3