kdtree/
distance.rs

1//! Defines different distance metrics, in simplest case it defines the
2//! euclidean distance which is no more than the square root of the sum of the
3//! squares of the distances in each dimension.
4
5use num_traits::Float;
6
7/// Returns the squared euclidean distance between two points. When you only
8/// need to compare distances, rather than having the exact distance between
9/// the points, this metric is benefitial because it avoids the expensive square
10/// root computation.
11///
12/// # Examples
13///
14/// ```rust
15/// use kdtree::distance::squared_euclidean;
16///
17/// assert!(0.0 == squared_euclidean(&[0.0, 0.0], &[0.0, 0.0]));
18/// assert!(2.0 == squared_euclidean(&[0.0, 0.0], &[1.0, 1.0]));
19/// assert!(1.0 == squared_euclidean(&[0.0, 0.0], &[1.0, 0.0]));
20/// ```
21///
22/// # Panics
23///
24/// Only in debug mode, the length of the slices at input will be compared.
25/// If they do not match, there will be a panic:
26///
27/// ```rust,should_panic
28/// # use kdtree::distance::squared_euclidean;
29/// // this is broken
30/// let _ = squared_euclidean(&[0.0, 0.0], &[1.0, 0.0, 0.0]);
31/// ```
32pub fn squared_euclidean<T: Float>(a: &[T], b: &[T]) -> T {
33    debug_assert_eq!(a.len(), b.len());
34    a.iter()
35        .zip(b.iter())
36        .map(|(x, y)| ((*x) - (*y)) * ((*x) - (*y)))
37        .fold(T::zero(), ::std::ops::Add::add)
38}