argmin_math/nalgebra_m/
l2norm.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::ArgminL2Norm;
9
10use nalgebra::{
11    base::{dimension::Dim, storage::Storage},
12    Matrix, SimdComplexField,
13};
14
15impl<N, R, C, S> ArgminL2Norm<N::SimdRealField> for Matrix<N, R, C, S>
16where
17    N: SimdComplexField,
18    R: Dim,
19    C: Dim,
20    S: Storage<N, R, C>,
21{
22    #[inline]
23    fn l2_norm(&self) -> N::SimdRealField {
24        self.norm()
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use super::*;
31    use approx::assert_relative_eq;
32    use nalgebra::Vector2;
33    use paste::item;
34
35    macro_rules! make_test {
36        ($t:ty) => {
37            item! {
38                #[test]
39                fn [<test_norm_ $t>]() {
40                    let a = Vector2::new(4 as $t, 3 as $t);
41                    let res = <Vector2<$t> as ArgminL2Norm<$t>>::l2_norm(&a);
42                    let target = 5 as $t;
43                    assert_relative_eq!(target as $t, res as $t, epsilon = $t::EPSILON);
44                }
45            }
46        };
47    }
48
49    macro_rules! make_test_signed {
50        ($t:ty) => {
51            item! {
52                #[test]
53                fn [<test_norm_signed_ $t>]() {
54                    let a = Vector2::new(-4 as $t, -3 as $t);
55                    let res = <Vector2<$t> as ArgminL2Norm<$t>>::l2_norm(&a);
56                    let target = 5 as $t;
57                    assert_relative_eq!(target as $t, res as $t, epsilon = $t::EPSILON);
58                }
59            }
60        };
61    }
62
63    make_test!(f32);
64    make_test!(f64);
65
66    make_test_signed!(f32);
67    make_test_signed!(f64);
68}