core practice · coding problem
Implement similarity metrics
Implement cosine similarity, dot product, and L2 distance. Show that on normalized vectors, cosine and dot product produce the same ranking.
The mechanism
Cosine measures angle (direction), dot product measures angle and magnitude, L2 measures straight-line distance. On normalized vectors cosine and dot product rank identically, and L2 becomes a monotonic function of them.
Expected evidence
Three functions; a demonstration that normalized cosine == dot ranking.
Try this drill in the practice workspace →
Hints when you need them
- Cosine = dot / (‖a‖·‖b‖).
- On unit vectors L2² = 2 − 2·cosine.
Watch for these mistakes
- Mixing distance metrics between indexing and querying
- Using dot product on un-normalized vectors and being surprised by magnitude bias
- Assuming the metric does not matter for the chosen index