Cosine similarity
Semantic search compares embeddings with cosine similarity. Implement it and cover the edge cases: different lengths and zero vectors.
Write cosine(a, b) that returns the dot product of a and b divided by the product of their norms: dot(a, b) / (|a| * |b|). The result goes from -1 (opposite) to 1 (same direction).
Throw an error when the vectors have different lengths. If either one is the zero vector (norm 0), return 0 instead of NaN.
Challenges 0/5
- Same vector gives 1, opposite -1 and perpendicular 0
- cosine([1,2,3],[4,5,6]) is 0.97463...
- Does not depend on the vector's scale
- Throws on different lengths
- A zero vector returns 0
function cosine(a, b) {
// dot product divided by the product of the norms
let dot = 0;
for (let i = 0; i < a.length; i++) dot += a[i] * b[i];
return dot;
}
console.log(cosine([1, 2, 3], [4, 5, 6]));Console output appears here (console.log).
Go deeper: the related guide →
This in production, with your data? Let's talk for 15 minutes →