Similarity Metrics and Vector Math
Harry
· 13 Sep 2026
· 3 views
Dot Product
The dot product sums the products of matching dimensions. It is fast and reflects both direction and magnitude, which suits recommendations where popularity matters.
Cosine Similarity
Cosine divides the dot product by the lengths of both vectors, so magnitude stops mattering. It is the standard metric for text and semantic search.
Euclidean (L2) Distance
L2 measures the straight-line distance between vectors. Smaller means closer. It is intuitive for embeddings where magnitude is meaningful, such as image features.
Apply It Yourself
import numpy as np
a = np.array([0.1, 0.3, 0.9, 0.2])
b = np.array([0.12, 0.28, 0.85, 0.21])
c = np.array([0.9, 0.1, 0.0, 0.4])
def cosine(x, y):
return float(x.dot(y) / (np.linalg.norm(x) * np.linalg.norm(y)))
print(cosine(a, b)) # close to 1 (similar)
print(cosine(a, c)) # much lower (dissimilar)
print(np.linalg.norm(a - b)) # L2 distance between a and bWhich Metric to Pick
- Cosine - Text, semantics, most RAG workloads.
- Dot product - Normalized vectors or magnitude-aware ranking.
- L2 - Geometric features and anomaly-style tasks.
Key Points
- Cosine ignores magnitude; dot product and L2 use it.
- Normalizing vectors makes cosine and dot equivalent.
- Match the metric to your data and ranking intent.
- Keep the same metric for index config and queries.