Skip to main content

quantum_planning/
complex.rs

1//! A minimal complex number over `f64`, the amplitude type of the simulator.
2
3use core::ops::{Add, Mul, Neg, Sub};
4
5/// A complex number `re + i·im` with `f64` parts.
6///
7/// The type has only the operations the simulator needs. Arithmetic follows IEEE 754: NaN
8/// and infinities propagate and are not checked.
9#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub struct Complex {
11    /// The real part.
12    pub re: f64,
13    /// The imaginary part.
14    pub im: f64,
15}
16
17impl Complex {
18    /// The additive identity, `0`.
19    pub const ZERO: Self = Self::new(0.0, 0.0);
20
21    /// The multiplicative identity, `1`.
22    pub const ONE: Self = Self::new(1.0, 0.0);
23
24    /// Makes the complex number `re + i·im`.
25    #[must_use]
26    pub const fn new(re: f64, im: f64) -> Self {
27        Self { re, im }
28    }
29
30    /// Makes the complex number `e^(i·angle)`, with `angle` in radians.
31    #[must_use]
32    pub fn from_angle(angle: f64) -> Self {
33        Self::new(libm::cos(angle), libm::sin(angle))
34    }
35
36    /// Returns the squared magnitude `re² + im²`, the measurement probability of an amplitude.
37    #[must_use]
38    pub fn norm_sqr(self) -> f64 {
39        self.re * self.re + self.im * self.im
40    }
41
42    /// Multiplies both parts by the real number `factor`.
43    #[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/// Unit tests for the complex arithmetic.
85#[cfg(test)]
86mod tests {
87    use super::Complex;
88
89    /// `i · i = -1`, and `e^(iπ/2) = i` within rounding.
90    #[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}