|
24 | 24 | fn l2_dist(&self, other: &ArrayBase<S, D>) -> f64
|
25 | 25 | where
|
26 | 26 | A: AddAssign + Clone + Signed + ToPrimitive;
|
| 27 | + |
| 28 | + fn l1_dist(&self, other: &ArrayBase<S, D>) -> A |
| 29 | + where |
| 30 | + A: AddAssign + Clone + Signed; |
27 | 31 | }
|
28 | 32 |
|
29 | 33 | impl<A, S, D> DeviationExt<A, S, D> for ArrayBase<S, D>
|
|
74 | 78 | {
|
75 | 79 | self.sq_l2_dist(other).to_f64().unwrap().sqrt()
|
76 | 80 | }
|
| 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 | + } |
77 | 95 | }
|
78 | 96 |
|
79 | 97 | #[cfg(test)]
|
@@ -133,4 +151,15 @@ mod tests {
|
133 | 151 |
|
134 | 152 | assert_eq!(a.l2_dist(&b), 2.0);
|
135 | 153 | }
|
| 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 | + } |
136 | 165 | }
|
0 commit comments