argmin_math/primitives/
conj.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::ArgminConj;
9use num_complex::Complex;
10
11macro_rules! make_conj {
12    ($t:ty) => {
13        impl ArgminConj for $t {
14            #[inline]
15            fn conj(&self) -> $t {
16                *self
17            }
18        }
19    };
20}
21
22macro_rules! make_complex_conj {
23    ($t:ty) => {
24        impl ArgminConj for $t {
25            #[inline]
26            fn conj(&self) -> $t {
27                Complex::conj(self)
28            }
29        }
30    };
31}
32
33make_conj!(i8);
34make_conj!(i16);
35make_conj!(i32);
36make_conj!(i64);
37make_conj!(u8);
38make_conj!(u16);
39make_conj!(u32);
40make_conj!(u64);
41make_conj!(f32);
42make_conj!(f64);
43make_complex_conj!(Complex<i8>);
44make_complex_conj!(Complex<i16>);
45make_complex_conj!(Complex<i32>);
46make_complex_conj!(Complex<i64>);
47make_complex_conj!(Complex<f32>);
48make_complex_conj!(Complex<f64>);
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53    use approx::assert_relative_eq;
54    use paste::item;
55
56    macro_rules! make_test_complex {
57        ($t:ty) => {
58            item! {
59                #[test]
60                fn [<test_complex_conj_ $t>]() {
61                    let a = 8 as $t;
62                    let b = 34 as $t;
63                    let res = <Complex<$t> as ArgminConj>::conj(&Complex::new(a, b));
64                    assert_relative_eq!(a as f64, res.re as f64, epsilon = f64::EPSILON);
65                    assert_relative_eq!(-b as f64, res.im as f64, epsilon = f64::EPSILON);
66                }
67            }
68        };
69    }
70
71    macro_rules! make_test {
72        ($t:ty) => {
73            item! {
74                #[test]
75                fn [<test_conj_ $t>]() {
76                    let a = 8 as $t;
77                    let res = <$t as ArgminConj>::conj(&a);
78                    assert_relative_eq!(a as f64, res as f64, epsilon = f64::EPSILON);
79                }
80            }
81        };
82    }
83
84    make_test_complex!(i8);
85    make_test_complex!(i16);
86    make_test_complex!(i32);
87    make_test_complex!(i64);
88    make_test_complex!(f32);
89    make_test_complex!(f64);
90    make_test!(i8);
91    make_test!(u8);
92    make_test!(i16);
93    make_test!(u16);
94    make_test!(i32);
95    make_test!(u32);
96    make_test!(i64);
97    make_test!(u64);
98    make_test!(f32);
99    make_test!(f64);
100}