From 3b35b9b5423d8844e655533c4ee56ca80012b390 Mon Sep 17 00:00:00 2001 From: Chris Watson Date: Mon, 17 Jun 2019 15:18:33 -0700 Subject: [PATCH] Added cosine distance function --- src/apatite.cr | 7 ++++++- src/apatite/linear_algebra/vector.cr | 7 ++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/apatite.cr b/src/apatite.cr index 8f3235e..8a72602 100644 --- a/src/apatite.cr +++ b/src/apatite.cr @@ -132,7 +132,7 @@ module Apatite end end - # Compute the cosine similarity between two vectors. + # Compute the cosine similarity of two vectors. def similarity(x, y) dot(x, y) / ( Math.sqrt(dot(x, x)) * @@ -140,6 +140,11 @@ module Apatite ) end + # Compute the cosine distance between two vectors. + def cosine(x, y) + 1.0 - similarity(x, y) + end + # Returns the angle between this vector and another in radians. # If the vectors are mirrored across their axes this will return `nil`. def angle_from(a, b) diff --git a/src/apatite/linear_algebra/vector.cr b/src/apatite/linear_algebra/vector.cr index 207b755..0673b79 100644 --- a/src/apatite/linear_algebra/vector.cr +++ b/src/apatite/linear_algebra/vector.cr @@ -450,11 +450,16 @@ module Apatite::LinearAlgebra Apatite.angle_from(self, vector) end - # Compute the cosine similarity between this vector and another. + # Compute the cosine similarity of this vector and another. def similarity(other) Apatite.similarity(self, other) end + # Compute the cosine distance between this vector and another. + def cosine(other) + Apatite.cosine(self, other) + end + # Returns whether the vectors are parallel to each other. def parallel_to?(vector) Apatite.parallel_to?(self, vector)