From 534445b244759df3f9ffc5ecb2f2ef135de40459 Mon Sep 17 00:00:00 2001 From: hachem Date: Sun, 15 Sep 2024 18:09:43 +0200 Subject: Make complex a Numeric --- libmu/src/maths/complex.rs | 13 +++++++- libmu/src/maths/numeric_types.rs | 66 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) (limited to 'libmu') 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 { pub real: T, pub imaginary: T, @@ -49,6 +49,17 @@ impl Complex { } } +impl ops::Neg for Complex { + type Output = Complex; + + fn neg(self) -> Complex { + Complex { + real: -self.real, + imaginary: -self.imaginary, + } + } +} + impl ops::Add for Complex { type Output = Complex; 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 { + 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 { + 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 { + fn zero() -> Self { + Complex::new(0.0, 0.0) + } + + fn one() -> Self { + Complex::new(1.0, 0.0) + } +} + +impl Numeric for Complex { + fn zero() -> Self { + Complex::new(0.0, 0.0) + } + + fn one() -> Self { + Complex::new(1.0, 0.0) + } +} -- cgit v1.3