Skip to content

Commit 6ac551c

Browse files
committed
Add norm_{l1,l2,max} in Vector crate
1 parent e0910aa commit 6ac551c

File tree

1 file changed

+45
-6
lines changed

1 file changed

+45
-6
lines changed

src/vector.rs

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,57 @@
11
//! Define trait for vectors
22
3-
use ndarray::{LinalgScalar, Array, Ix1};
3+
use std::iter::Sum;
4+
use ndarray::{LinalgScalar, ArrayBase, Data, Dimension};
45
use num_traits::float::Float;
56

67
/// Methods for vectors
78
pub trait Vector {
89
type Scalar;
10+
/// rename of norm_l2
11+
fn norm(&self) -> Self::Scalar {
12+
self.norm_l2()
13+
}
14+
/// L-1 norm
15+
fn norm_l1(&self) -> Self::Scalar;
916
/// L-2 norm
10-
fn norm(&self) -> Self::Scalar;
17+
fn norm_l2(&self) -> Self::Scalar;
18+
/// maximum norm
19+
fn norm_max(&self) -> Self::Scalar;
1120
}
1221

13-
impl<A: Float + LinalgScalar> Vector for Array<A, Ix1> {
14-
type Scalar = A;
15-
fn norm(&self) -> Self::Scalar {
16-
self.dot(&self).sqrt()
22+
impl<A, S, D, T> Vector for ArrayBase<S, D>
23+
where A: LinalgScalar + Squared<Output = T>,
24+
T: Float + Sum,
25+
S: Data<Elem = A>,
26+
D: Dimension
27+
{
28+
type Scalar = T;
29+
fn norm_l1(&self) -> Self::Scalar {
30+
self.iter().map(|x| x.sq_abs()).sum()
31+
}
32+
fn norm_l2(&self) -> Self::Scalar {
33+
self.iter().map(|x| x.squared()).sum::<T>().sqrt()
34+
}
35+
fn norm_max(&self) -> Self::Scalar {
36+
self.iter().fold(T::zero(), |f, &val| {
37+
let v = val.sq_abs();
38+
if f > v { f } else { v }
39+
})
40+
}
41+
}
42+
43+
pub trait Squared {
44+
type Output;
45+
fn squared(&self) -> Self::Output;
46+
fn sq_abs(&self) -> Self::Output;
47+
}
48+
49+
impl<A: Float> Squared for A {
50+
type Output = A;
51+
fn squared(&self) -> A {
52+
*self * *self
53+
}
54+
fn sq_abs(&self) -> A {
55+
self.abs()
1756
}
1857
}

0 commit comments

Comments
 (0)