fast_distances/distances/
euclidean.rs

1use ndarray::ArrayView1;
2use num::{Float, Zero};
3
4/// Computes the Euclidean distance between two vectors.
5///
6/// # Arguments
7///
8/// * `x` - A 1-dimensional array view of type `T`.
9/// * `y` - Another 1-dimensional array view of type `T`.
10///
11/// # Returns
12///
13/// The Euclidean distance between `x` and `y`, of type `T`.
14///
15/// # Panics
16///
17/// This function will panic if the input arrays do not have the same length.
18pub 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::*; // Import the function to be tested
38
39    #[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()); // This should panic
75    }
76}