From 2da48d7549e2db3f0e8ba01523095d2f3764ce0a Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Sun, 27 Nov 2016 13:37:22 +0200 Subject: Added conjugating and multiplication --- src/complex.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) (limited to 'src/complex.rs') diff --git a/src/complex.rs b/src/complex.rs index 1a8bc20..960dba4 100644 --- a/src/complex.rs +++ b/src/complex.rs @@ -1,4 +1,4 @@ -use std::ops::{Add, Sub, Mul}; +use std::ops::{Add, Sub, Mul, Neg}; use ::num_traits::{Trig, Pow}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -12,17 +12,22 @@ impl Complex { Complex{real: real, imag: imag} } } +impl Complex where T: Neg { + pub fn conjugate(self) -> Complex { + Complex::new(self.real, -self.imag) + } +} -impl Complex where T: Trig + Mul + Copy { +impl Complex where T: Trig + Mul + Copy { pub fn from_polar(r: T, theta: T) -> Complex { let real = r*theta.cos(); let imag = r*theta.sin(); Complex::new(real, imag) } } -impl Complex where T: Trig + Pow + Add + Copy { +impl Complex where T: Trig + Pow + Add + Copy { pub fn to_polar(self) -> (T, T) { - let r = (self.real.powi(2) + self.imag.powi(2)).sqrt(); + let r = (self.real.pow(2) + self.imag.pow(2)).sqrt(); let theta = self.imag.atan2(self.real); (r, theta) } @@ -48,6 +53,16 @@ impl Sub for Complex where T: Sub + Copy { } } +impl Mul for Complex where T: Add + Mul + Sub + Copy { + type Output = Complex; + + fn mul(self, other: Self) -> Self { + let real = (self.real * other.real) - (self.imag * other.imag); + let imag = (self.real * other.imag) + (self.imag * other.real); + Complex::new(real, imag) + } +} + #[cfg(test)] mod tests { use super::*; @@ -67,6 +82,13 @@ mod tests { assert_eq!(a-b, Complex::new(4, 3)); } + #[test] + fn multiplication() { + let a = Complex::new(3, 4); + let b = Complex::new(2, 3); + assert_eq!(a*b, Complex::new(-6, 17)); + } + #[test] fn from_polar() { -- cgit v1.2.3