1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
use ndarray::{prelude::*, Data};
pub trait Norm {
type Output;
fn norm_l1(&self) -> Self::Output;
fn norm_l2(&self) -> Self::Output;
fn norm_max(&self) -> Self::Output;
}
impl<A, S, D> Norm for ArrayBase<S, D>
where
A: NdFloat + std::iter::Sum,
S: Data<Elem = A>,
D: Dimension,
{
type Output = A;
fn norm_l1(&self) -> Self::Output {
self.iter().map(|x| x.abs()).sum()
}
fn norm_l2(&self) -> Self::Output {
self.iter().map(|&x| x * x).sum::<A>().sqrt()
}
fn norm_max(&self) -> Self::Output {
self.iter().fold(A::zero(), |f, &val| val.abs().max(f))
}
}
#[cfg(test)]
mod tests {
use approx::assert_abs_diff_eq;
use super::*;
#[test]
fn norms() {
let a = array![[1.0f64, -3.], [2., -8.]];
assert_abs_diff_eq!(a.norm_l1(), 14.);
assert_abs_diff_eq!(a.norm_l2(), 78.0f64.sqrt());
assert_abs_diff_eq!(a.norm_max(), 8.);
}
}