complex_algebra/
complex.rs

1mod add;
2mod cos;
3mod cosh;
4mod div;
5mod exp;
6mod mul;
7mod neg;
8mod pow;
9mod sin;
10mod sinh;
11mod sub;
12pub use cos::Cos;
13pub use cosh::Cosh;
14pub use exp::Exp;
15pub use pow::Pow;
16pub use sin::Sin;
17pub use sinh::Sinh;
18use std::ops::{Add, Mul, Neg};
19
20use crate::cos_macro;
21use crate::cosh_macro;
22use crate::exp_macro;
23use crate::pow_macro;
24use crate::pow_non_neg_macro;
25use crate::sin_macro;
26use crate::sinh_macro;
27
28#[allow(non_camel_case_types)]
29#[derive(Debug, PartialEq, Copy, Clone)]
30pub struct c<T: Copy + PartialEq>(pub T, pub T);
31
32impl<T: Copy + PartialEq> c<T> {
33    /// Extracts the real part of the complex number.
34    #[allow(non_snake_case)]
35    pub fn Re(&self) -> T {
36        self.0
37    }
38
39    /// Extracts the imaginary part of the complex number.
40    #[allow(non_snake_case)]
41    pub fn Im(&self) -> T {
42        self.1
43    }
44}
45
46/// Returns the conjugated complex number.
47impl<T: Copy + PartialEq + Neg<Output = T>> c<T> {
48    pub fn conj(&self) -> c<T> {
49        c(self.0, -self.1)
50    }
51}
52
53/// Returns the square of the euclidean norm: `|z|^2`
54impl<T: Copy + PartialEq + Add<Output = T> + Mul<Output = T>> c<T> {
55    pub fn r_square(&self) -> T {
56        self.0 * self.0 + self.1 * self.1
57    }
58}
59
60exp_macro!(f64);
61exp_macro!(f32);
62pow_non_neg_macro!(u8, u32, u64, u128);
63pow_macro!(i8, i32, i64, i128; u8, u32, u64, u128; f32);
64pow_macro!(i8, i32, i64, i128; u8, u32, u64, u128; f64);
65cos_macro!(f32);
66cos_macro!(f64);
67sin_macro!(f32);
68sin_macro!(f64);
69sinh_macro!(f32);
70sinh_macro!(f64);
71cosh_macro!(f32);
72cosh_macro!(f64);
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77
78    #[test]
79    fn test_conj() {
80        let z = c(1, 2);
81        assert_eq!(z.conj(), c(1, -2));
82    }
83
84    #[test]
85    fn test_r_square() {
86        let z = c(1, 2);
87        assert_eq!(z.r_square(), (c(1, 2) * c(1, 2).conj()).Re());
88    }
89}