quantum_planning/
complex.rs1use core::ops::{Add, Mul, Neg, Sub};
4
5#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub struct Complex {
11 pub re: f64,
13 pub im: f64,
15}
16
17impl Complex {
18 pub const ZERO: Self = Self::new(0.0, 0.0);
20
21 pub const ONE: Self = Self::new(1.0, 0.0);
23
24 #[must_use]
26 pub const fn new(re: f64, im: f64) -> Self {
27 Self { re, im }
28 }
29
30 #[must_use]
32 pub fn from_angle(angle: f64) -> Self {
33 Self::new(libm::cos(angle), libm::sin(angle))
34 }
35
36 #[must_use]
38 pub fn norm_sqr(self) -> f64 {
39 self.re * self.re + self.im * self.im
40 }
41
42 #[must_use]
44 pub fn scale(self, factor: f64) -> Self {
45 Self::new(self.re * factor, self.im * factor)
46 }
47}
48
49impl Add for Complex {
50 type Output = Self;
51
52 fn add(self, rhs: Self) -> Self {
53 Self::new(self.re + rhs.re, self.im + rhs.im)
54 }
55}
56
57impl Sub for Complex {
58 type Output = Self;
59
60 fn sub(self, rhs: Self) -> Self {
61 Self::new(self.re - rhs.re, self.im - rhs.im)
62 }
63}
64
65impl Mul for Complex {
66 type Output = Self;
67
68 fn mul(self, rhs: Self) -> Self {
69 Self::new(
70 self.re * rhs.re - self.im * rhs.im,
71 self.re * rhs.im + self.im * rhs.re,
72 )
73 }
74}
75
76impl Neg for Complex {
77 type Output = Self;
78
79 fn neg(self) -> Self {
80 Self::new(-self.re, -self.im)
81 }
82}
83
84#[cfg(test)]
86mod tests {
87 use super::Complex;
88
89 #[test]
91 fn multiplies_and_rotates() {
92 let i = Complex::new(0.0, 1.0);
93 let quarter_turn = Complex::from_angle(core::f64::consts::FRAC_PI_2);
94
95 assert_eq!(i * i, -Complex::ONE);
96 assert!((quarter_turn - i).norm_sqr() < 1e-30);
97 assert_eq!((Complex::new(3.0, 4.0)).norm_sqr(), 25.0);
98 }
99}