Calculate the cosine similarity between two vectors used in embedding comparisons.
Cosine similarity measures the cosine of the angle between two vectors: cos(θ) = (A·B) / (‖A‖ × ‖B‖). It ranges from -1 (opposite direction) to 1 (identical direction), with 0 meaning orthogonal (unrelated). Unlike Euclidean distance, cosine similarity ignores vector magnitude and focuses purely on direction, which is why it's the standard metric for comparing text and image embeddings in semantic search, RAG retrieval, and recommendation systems — where the direction of an embedding vector encodes meaning more reliably than its length.
cosine_similarity = dot(A, B) / (norm(A) * norm(B))
A similarity of 1 means the two vectors point in exactly the same direction, indicating maximum similarity (e.g. semantically identical embeddings).
Embedding magnitude often reflects factors like text length rather than meaning, so cosine similarity — which normalizes by magnitude — better captures semantic similarity independent of vector length.
Yes, it ranges from -1 to 1. Negative values indicate the vectors point in substantially opposite directions, which is uncommon for typical embedding models but possible mathematically.
Cosine distance is simply 1 minus cosine similarity, converting a similarity score (higher is more similar) into a distance metric (lower is more similar), which is convenient for nearest-neighbor search algorithms.