diff options
Diffstat (limited to 'libmu/src/maths')
| -rw-r--r-- | libmu/src/maths/complex.rs | 13 | ||||
| -rw-r--r-- | libmu/src/maths/numeric_types.rs | 66 |
2 files changed, 78 insertions, 1 deletions
diff --git a/libmu/src/maths/complex.rs b/libmu/src/maths/complex.rs index 79212b6..931b030 100644 --- a/libmu/src/maths/complex.rs +++ b/libmu/src/maths/complex.rs @@ -1,7 +1,7 @@ use crate::numeric_types::Float; use core::{fmt, ops}; -#[derive(Copy, Clone)] +#[derive(Copy, Clone, PartialOrd, PartialEq)] pub struct Complex<T: Float> { pub real: T, pub imaginary: T, @@ -49,6 +49,17 @@ impl<T: Float> Complex<T> { } } +impl<T: Float> ops::Neg for Complex<T> { + type Output = Complex<T>; + + fn neg(self) -> Complex<T> { + Complex { + real: -self.real, + imaginary: -self.imaginary, + } + } +} + impl<T: Float> ops::Add for Complex<T> { type Output = Complex<T>; diff --git a/libmu/src/maths/numeric_types.rs b/libmu/src/maths/numeric_types.rs index 42e2fb7..f9833dc 100644 --- a/libmu/src/maths/numeric_types.rs +++ b/libmu/src/maths/numeric_types.rs @@ -1,5 +1,7 @@ use core::ops; +use super::Complex; + pub trait Numeric: Copy + PartialOrd @@ -43,6 +45,50 @@ impl Float for f64 { } } +impl Float for Complex<f32> { + fn sqrt(self) -> Self { + let r = self.abs(); + let theta = self.phase(); + + let sqrt_r = libm::sqrtf(r); + let sqrt_theta = theta / 2.0; + + Complex::new( + sqrt_r * libm::cosf(sqrt_theta), + sqrt_r * libm::sinf(sqrt_theta), + ) + } + + fn atan2(y: Self, x: Self) -> Self { + Complex::new( + libm::atan2f(y.real, x.real), + libm::atan2f(y.imaginary, x.imaginary), + ) + } +} + +impl Float for Complex<f64> { + fn sqrt(self) -> Self { + let r = self.abs(); + let theta = self.phase(); + + let sqrt_r = libm::sqrt(r); + let sqrt_theta = theta / 2.0; + + Complex::new( + sqrt_r * libm::cos(sqrt_theta), + sqrt_r * libm::sin(sqrt_theta), + ) + } + + fn atan2(y: Self, x: Self) -> Self { + Complex::new( + libm::atan2(y.real, x.real), + libm::atan2(y.imaginary, x.imaginary), + ) + } +} + impl Integer for i64 {} impl Integer for i32 {} @@ -85,3 +131,23 @@ impl Numeric for f64 { 1.0 } } + +impl Numeric for Complex<f32> { + fn zero() -> Self { + Complex::new(0.0, 0.0) + } + + fn one() -> Self { + Complex::new(1.0, 0.0) + } +} + +impl Numeric for Complex<f64> { + fn zero() -> Self { + Complex::new(0.0, 0.0) + } + + fn one() -> Self { + Complex::new(1.0, 0.0) + } +} |
