Skip to main content

rescale_core/fft/
complex.rs

1//! Struktur bilangan kompleks f32 untuk komputasi Fourier Transform.
2
3use std::ops::{Add, AddAssign, Mul, Sub};
4
5#[derive(Debug, Clone, Copy, PartialEq, Default)]
6pub struct Complex {
7    pub re: f32,
8    pub im: f32,
9}
10
11impl Complex {
12    #[inline(always)]
13    pub fn new(re: f32, im: f32) -> Self {
14        Self { re, im }
15    }
16
17    /// Membuat complex number dari representasi polar e^(i * theta)
18    #[inline(always)]
19    pub fn from_polar(magnitude: f32, theta: f32) -> Self {
20        Self {
21            re: magnitude * theta.cos(),
22            im: magnitude * theta.sin(),
23        }
24    }
25
26    /// Menghitung magnitudo absolut / modulus |z| = sqrt(re^2 + im^2)
27    #[inline(always)]
28    pub fn magnitude(self) -> f32 {
29        (self.re * self.re + self.im * self.im).sqrt()
30    }
31
32    /// Menghitung power spectrum |z|^2 = re^2 + im^2
33    #[inline(always)]
34    pub fn power(self) -> f32 {
35        self.re * self.re + self.im * self.im
36    }
37
38    /// Menghitung sudut fase arg(z) = atan2(im, re) dalam radian
39    #[inline(always)]
40    pub fn phase(self) -> f32 {
41        self.im.atan2(self.re)
42    }
43
44    /// Konjugat kompleks: conj(a + bi) = a - bi
45    #[inline(always)]
46    pub fn conjugate(self) -> Self {
47        Self {
48            re: self.re,
49            im: -self.im,
50        }
51    }
52}
53
54impl Add for Complex {
55    type Output = Self;
56    #[inline(always)]
57    fn add(self, rhs: Self) -> Self::Output {
58        Self {
59            re: self.re + rhs.re,
60            im: self.im + rhs.im,
61        }
62    }
63}
64
65impl AddAssign for Complex {
66    #[inline(always)]
67    fn add_assign(&mut self, rhs: Self) {
68        self.re += rhs.re;
69        self.im += rhs.im;
70    }
71}
72
73impl Sub for Complex {
74    type Output = Self;
75    #[inline(always)]
76    fn sub(self, rhs: Self) -> Self::Output {
77        Self {
78            re: self.re - rhs.re,
79            im: self.im - rhs.im,
80        }
81    }
82}
83
84impl Mul for Complex {
85    type Output = Self;
86    #[inline(always)]
87    fn mul(self, rhs: Self) -> Self::Output {
88        // (a + bi)(c + di) = (ac - bd) + (ad + bc)i
89        Self {
90            re: self.re * rhs.re - self.im * rhs.im,
91            im: self.re * rhs.im + self.im * rhs.re,
92        }
93    }
94}
95
96impl Mul<f32> for Complex {
97    type Output = Self;
98    #[inline(always)]
99    fn mul(self, scalar: f32) -> Self::Output {
100        Self {
101            re: self.re * scalar,
102            im: self.im * scalar,
103        }
104    }
105}