Skip to content

Commit 6e93e34

Browse files
committed
deviation: Implement l1_dist
1 parent 9ba5f35 commit 6e93e34

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/deviation.rs

+29
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ where
2424
fn l2_dist(&self, other: &ArrayBase<S, D>) -> f64
2525
where
2626
A: AddAssign + Clone + Signed + ToPrimitive;
27+
28+
fn l1_dist(&self, other: &ArrayBase<S, D>) -> A
29+
where
30+
A: AddAssign + Clone + Signed;
2731
}
2832

2933
impl<A, S, D> DeviationExt<A, S, D> for ArrayBase<S, D>
@@ -74,6 +78,20 @@ where
7478
{
7579
self.sq_l2_dist(other).to_f64().unwrap().sqrt()
7680
}
81+
82+
fn l1_dist(&self, other: &ArrayBase<S, D>) -> A
83+
where
84+
A: AddAssign + Clone + Signed,
85+
{
86+
let mut r = A::zero();
87+
88+
Zip::from(self).and(other).apply(|self_i, other_i| {
89+
let (a, b) = (self_i.clone(), other_i.clone());
90+
r += (a - b).abs();
91+
});
92+
93+
r
94+
}
7795
}
7896

7997
#[cfg(test)]
@@ -133,4 +151,15 @@ mod tests {
133151

134152
assert_eq!(a.l2_dist(&b), 2.0);
135153
}
154+
155+
#[test]
156+
fn test_l1_dist() {
157+
let a = array![1., 2., 3., 4., 5., 6., 7.];
158+
let b = array![1., 3., 3., 4., 6., 7., 8.];
159+
let c = array![[1, 2], [3, 4], [5, 6]];
160+
let d = array![[1, 2], [4, 3], [5, 6]];
161+
162+
assert_eq!(a.l1_dist(&b), (&a - &b).mapv(f64::abs).sum());
163+
assert_eq!(c.l1_dist(&d), (&c - &d).mapv(i32::abs).sum());
164+
}
136165
}

0 commit comments

Comments
 (0)