argmin_math/vec/
signum.rs1use crate::ArgminSignum;
9use num_complex::Complex;
10
11macro_rules! make_signum {
12 ($t:ty) => {
13 impl ArgminSignum for Vec<$t> {
14 fn signum(mut self) -> Self {
15 for x in &mut self {
16 *x = x.signum();
17 }
18 self
19 }
20 }
21 };
22}
23
24macro_rules! make_signum_complex {
25 ($t:ty) => {
26 impl ArgminSignum for Vec<$t> {
27 fn signum(mut self) -> Self {
28 for x in &mut self {
29 x.re = x.re.signum();
30 x.im = x.im.signum();
31 }
32 self
33 }
34 }
35 };
36}
37
38make_signum!(i8);
39make_signum!(i16);
40make_signum!(i32);
41make_signum!(i64);
42make_signum!(f32);
43make_signum!(f64);
44make_signum_complex!(Complex<i8>);
45make_signum_complex!(Complex<i16>);
46make_signum_complex!(Complex<i32>);
47make_signum_complex!(Complex<i64>);
48make_signum_complex!(Complex<f32>);
49make_signum_complex!(Complex<f64>);
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54 use paste::item;
55
56 macro_rules! make_test {
57 ($t:ty) => {
58 item! {
59 #[test]
60 fn [<test_signum_complex_ $t>]() {
61 let x = vec![
62 Complex::new(1 as $t, 2 as $t),
63 Complex::new(4 as $t, -3 as $t),
64 Complex::new(-8 as $t, 4 as $t),
65 Complex::new(-8 as $t, -1 as $t),
66 ];
67 let y = vec![
68 Complex::new(1 as $t, 1 as $t),
69 Complex::new(1 as $t, -1 as $t),
70 Complex::new(-1 as $t, 1 as $t),
71 Complex::new(-1 as $t, -1 as $t),
72 ];
73 let res = <Vec<Complex<$t>> as ArgminSignum>::signum(x);
74 for i in 0..4 {
75 let tmp = y[i] - res[i];
76 let norm = ((tmp.re * tmp.re + tmp.im * tmp.im) as f64).sqrt();
77 assert!(norm < f64::EPSILON);
78 }
79 }
80 }
81
82 item! {
83 #[test]
84 fn [<test_signum_ $t>]() {
85 let x = vec![1 as $t, -4 as $t, 8 as $t];
86 let y = vec![1 as $t, -1 as $t, 1 as $t];
87 let res = <Vec<$t> as ArgminSignum>::signum(x);
88 for i in 0..3 {
89 let diff = (y[i] - res[i]).abs() as f64;
90 assert!(diff < f64::EPSILON);
91 }
92 }
93 }
94 };
95 }
96
97 make_test!(i8);
98 make_test!(i16);
99 make_test!(i32);
100 make_test!(i64);
101 make_test!(f32);
102 make_test!(f64);
103}