array_matrix/vector/
abs.rs

1use num_complex::Complex;
2use num_traits::Float;
3
4use crate::Vector;
5
6pub trait VAbs: Vector
7{
8    type Output;
9
10    /// Returns the square euclidian absolute value of any vector-array
11    /// 
12    /// ||u||²
13    /// 
14    /// # Examples
15    /// 
16    /// ```rust
17    /// let u = [1.0, 2.0];
18    /// let u_abs_sqr = u[0]*u[0] + u[1]*u[1];
19    /// 
20    /// assert_eq!(u.abs_sqr(), u_abs_sqr);
21    /// ```
22    fn abs_sqr(&self) -> Self::Output;
23    
24    /// Returns the euclidian absolute value of any vector-array
25    /// 
26    /// ||u||
27    /// 
28    /// # Examples
29    /// 
30    /// ```rust
31    /// let u = [1.0, 2.0];
32    /// let u_abs = (u[0]*u[0] + u[1]*u[1]).sqrt();
33    /// 
34    /// assert_eq!(u.abs(), u_abs);
35    /// ```
36    fn abs(&self) -> Self::Output;
37}
38
39impl<const N: usize> VAbs for [f32; N]
40{
41    type Output = f32;
42    fn abs_sqr(&self) -> Self::Output
43    {
44        self.iter().map(|x| x.abs().powi(2)).reduce(|a, b| a + b).unwrap_or(0.0)
45    }
46    fn abs(&self) -> Self::Output
47    {
48        self.abs_sqr().sqrt()
49    }
50}
51
52impl<const N: usize> VAbs for [f64; N]
53{
54    type Output = f64;
55    fn abs_sqr(&self) -> Self::Output
56    {
57        self.iter().map(|x| x.abs().powi(2)).reduce(|a, b| a + b).unwrap_or(0.0)
58    }
59    fn abs(&self) -> Self::Output
60    {
61        self.abs_sqr().sqrt()
62    }
63}
64
65impl<F: Float, const N: usize> VAbs for [Complex<F>; N]
66{
67    type Output = F;
68    fn abs_sqr(&self) -> Self::Output
69    {
70        self.iter().map(|x| x.norm_sqr()).reduce(|a, b| a + b).unwrap_or(F::zero())
71    }
72    fn abs(&self) -> Self::Output
73    {
74        self.abs_sqr().sqrt()
75    }
76}