Skip to content

Commit

Permalink
feat(vectors): add distCosine() (cosine similarity)
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 30, 2024
1 parent 66e4c19 commit 2af6010
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
37 changes: 37 additions & 0 deletions packages/vectors/src/dist-cosine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { DistanceFn } from "./api.js";

/**
* Cosine **similarity** metric. Result always in [-1,1] interval.
*
* @remarks
* Similar to: `dot(a, b) / (magSq(a) * magSq(b))`. Returns zero if one of the
* vectors is a zero-vector.
*
* Reference: https://en.wikipedia.org/wiki/Cosine_similarity
*
* @example
* ```ts tangle:../export/dist-cosine.ts
* import { distCosine } from "@thi.ng/vectors";
*
* console.log(
* distCosine([0, 1, 1, 0], [1, 1, 0, 0])
* );
* // 0.499999...
* ```
*
* @param a -
* @param b -
*/
export const distCosine: DistanceFn = (a, b) => {
let asum = 0;
let bsum = 0;
let dot = 0;
for (let i = 0, n = a.length; i < n; i++) {
const aa = a[i];
const bb = b[i];
asum += aa * aa;
bsum += bb * bb;
dot += aa * bb;
}
return asum && bsum ? dot / (Math.sqrt(asum) * Math.sqrt(bsum)) : 0;
};
1 change: 1 addition & 0 deletions packages/vectors/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export * from "./dist.js";
export * from "./dist-braycurtis.js";
export * from "./dist-canberra.js";
export * from "./dist-chebyshev.js";
export * from "./dist-cosine.js";
export * from "./dist-hamming.js";
export * from "./dist-haversine.js";
export * from "./dist-jaccard.js";
Expand Down

0 comments on commit 2af6010

Please sign in to comment.