LLM engineering · Easy · 8 min

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]));

Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.

Console output appears here (console.log).

Why this matters

Every semantic search ends in this sum: the query vector against the vector of each chunk. A vector database does it for you, but when a result looks wrong you need to know what it measures: the angle between two vectors, not their length. The edge cases in the exercise are the ones you meet in production: an empty text gives a zero vector, and mixing two embedding models gives different lengths. To pick a model for Spanish text, see our measured comparison of local embedding models.

Go deeper: the related guide →

This in production, with your data? Let's talk for 15 minutes →