fast_distances/distances/
euclidean.rs1use ndarray::ArrayView1;
2use num::{Float, Zero};
3
4pub fn euclidean<T>(x: &ArrayView1<T>, y: &ArrayView1<T>) -> T
19where
20 T: Float + Zero,
21{
22 assert_eq!(x.len(), y.len(), "Input arrays must have the same length.");
23
24 let mut result = T::zero();
25 for i in 0..x.len() {
26 let diff = x[i] - y[i];
27 result = result + diff * diff;
28 }
29
30 result.sqrt()
31}
32
33#[cfg(test)]
34mod tests {
35 use ndarray::arr1;
36
37 use super::*; #[test]
40 fn test_euclidean_f64() {
41 let x = arr1(&[1.0f64, 2.0, 3.0]);
42 let y = arr1(&[4.0f64, 5.0, 6.0]);
43
44 let dist = euclidean(&x.view(), &y.view());
45 assert!(
46 (dist - 5.196152422706632).abs() < 1e-6,
47 "Test failed for f64."
48 );
49 }
50
51 #[test]
52 fn test_euclidean_f32() {
53 let x = arr1(&[1.0f32, 2.0, 3.0]);
54 let y = arr1(&[4.0f32, 5.0, 6.0]);
55
56 let dist = euclidean(&x.view(), &y.view());
57 assert!((dist - 5.1961524).abs() < 1e-6, "Test failed for f32.");
58 }
59
60 #[test]
61 fn test_euclidean_zero_distance() {
62 let x = arr1(&[1.0f64, 2.0, 3.0]);
63 let y = arr1(&[1.0f64, 2.0, 3.0]);
64
65 let dist = euclidean(&x.view(), &y.view());
66 assert!((dist - 0.0).abs() < 1e-6, "Test failed for zero distance.");
67 }
68
69 #[test]
70 #[should_panic(expected = "Input arrays must have the same length.")]
71 fn test_euclidean_different_lengths() {
72 let x = arr1(&[1.0f64, 2.0]);
73 let y = arr1(&[4.0f64, 5.0, 6.0]);
74 euclidean(&x.view(), &y.view()); }
76}