Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/distance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ pub enum DistanceMetric {
/// The sum of all absolute differences between each dimension of two points.
/// Also known as L1 norm or city block.
Manhattan,
/// Measures the cosine of the angle between two vectors.
/// Range is [0, 2] for non-negative inputs, where 0 means identical direction, 2 means opposite directions.
/// Ignores magnitude, only considers orientation.
Cosine,
}

impl DistanceMetric {
Expand All @@ -31,6 +35,7 @@ impl DistanceMetric {
Self::Euclidean => euclidean_distance(a, b),
Self::Haversine => haversine_distance(a, b),
Self::Manhattan => manhattan_distance(a, b),
Self::Cosine => cosine_distance(a, b),
}
}
}
Expand All @@ -42,6 +47,7 @@ pub(crate) fn get_dist_func<T: Float>(metric: &DistanceMetric) -> impl Fn(&[T],
DistanceMetric::Euclidean => euclidean_distance,
DistanceMetric::Haversine => haversine_distance,
DistanceMetric::Manhattan => manhattan_distance,
DistanceMetric::Cosine => cosine_distance,
}
}

Expand Down Expand Up @@ -93,6 +99,28 @@ pub(crate) fn chebyshev_distance<T: Float>(a: &[T], b: &[T]) -> T {
.fold(T::zero(), T::max)
}

pub(crate) fn cosine_distance<T: Float>(a: &[T], b: &[T]) -> T {
assert_inputs(a, b);

let dot_product = a
.iter()
.zip(b.iter())
.map(|(x, y)| ((*x) * (*y)))
.fold(T::zero(), std::ops::Add::add);
let magnitude_a = a
.iter()
.map(|&x| x.powi(2))
.fold(T::zero(), std::ops::Add::add)
.sqrt();
let magnitude_b = b
.iter()
.map(|&x| x.powi(2))
.fold(T::zero(), std::ops::Add::add)
.sqrt();

T::one() - (dot_product / (magnitude_a * magnitude_b))
}

pub(crate) fn cylindrical_distance<T: Float>(a: &[T], b: &[T]) -> T {
assert_inputs(a, b);
assert_eq!(
Expand Down