If you've ever built a semantic search engine, you chose cosine similarity without ever really choosing it. A search engine like that turns every text into an embedding, a vector of numbers a model uses to represent it, then compares the question with each document using cosine similarity: the cosine of the angle between the two vectors. It equals when they point the same way and falls as they diverge, and the engine returns the texts with the highest values. It's the default in almost every vector database (the kind that stores vectors and returns the ones most similar to a given vector), the measure OpenAI recommends for its embeddings, and the one RAG tutorials take for granted. (Retrieval-augmented generation means finding the passages most similar to a question and handing them to the model so it can answer from them.)
Many libraries, though, give you not the similarity but its reverse, one minus the cosine, so
that a smaller value means "closer", as with any distance. SciPy, Python's scientific library, calls
it "Cosine distance".
In pgvector, PostgreSQL's vector extension, it's what the
<=> operator returns. In scikit-learn, the machine learning library, you ask for it with
metric="cosine". Sorting from smallest to largest is the same as sorting
from largest to smallest, so the search returns the same results either way. What
changes is the name: the similarity, turned inside out, is presented as a distance, and in
scikit-learn even as a metric.
Take three vectors of length one leaving the same point. A points horizontally, C points vertically, and B sits right in between at 45°. The cosine distance, , is between A and B and another between B and C, but between A and C it's . Going from A to C by way of B costs ; going straight costs .
Three vectors and the cosine distance: the direct route is longer than the detour.
No distance worth the name allows that. The direct route can't be longer than a detour: that's the triangle inequality, and the cosine distance doesn't satisfy it. So two things need to be kept apart. Cosine similarity, which ranks the results, isn't a distance at all; it's a score of resemblance. And the cosine distance built from it isn't a metric.
And yet the cosine is the right choice almost every time. That leaves two questions. The first is why it has won out over the dozens of ways of comparing two vectors. The second is what it costs that its distance isn't a metric: nothing in a search, but quite a lot in some other operations. Along the way we'll meet the measures it competes with and the cases where it stops being the right tool.
An embedding is a vector
An embedding is a vector a model uses to represent a piece of text: a word, a sentence, a whole document. A vector of dimensions is just numbers, and current models use hundreds or thousands (384, 768, 1,536 and 3,072 are common sizes). The model is trained so that texts with similar meanings get similar vectors. A vector of numbers is a point in -dimensional space, and it's usually drawn as an arrow from the origin to that point.
Two properties of a vector matter here. The first is its length, or norm:
The second is its direction: where it points.
To compare two vectors, the basic tool is the dot product: multiply coordinate by coordinate and add up the results. It has a geometric reading that ties it to the angle between the two vectors:
Solving for the cosine gives cosine similarity:
It's when the two vectors point the same way, when they're perpendicular and when they point in opposite directions. And it doesn't change if you stretch or shrink either vector: dividing by the lengths is precisely what removes them. The vectors and have a cosine of , even though the second is twice as long and the distance between their tips is .
That distance between the tips is the other classic comparison, the Euclidean distance: , the length of the vector that runs from one tip to the other. It sees direction and length together. The cosine sees only direction and throws away whatever was stored in the length. That act of discarding is the whole story: it explains both why the cosine is almost always the right choice and what it costs.
Similarity, distance and metric
Three words that are often used as synonyms actually name three different things.
A similarity is any score that grows the more two things resemble each other. It promises nothing else: no maximum value, not even that something is most similar to itself. The cosine is a similarity.
A distance, in the broad sense libraries use, is the opposite: a score that grows the more two things differ. Any similarity becomes one when you flip it, and is the "cosine distance" of SciPy and pgvector. It runs from (same direction) to (opposite directions).
A metric is a distance that obeys four rules. Here the word has its geometric sense, not the sense of evaluation metrics such as a classifier's accuracy. For any , , :
- . No distance is negative.
- only if . A distance of zero means "they're the same".
- . It doesn't matter where you measure from.
- . The triangle inequality: the direct route is never longer than a detour.
The fourth does the most work. It means that knowing two distances bounds the third: if is close to and is close to , then can't be far from . Everything that reasons about distances without computing them all relies on it.
Now let's check against the rules. It meets the first, because the cosine never exceeds , and the third, because the angle from to is the same as from to . The second fails: and are different vectors, yet their cosine distance is . At best it compares directions, not vectors. That one has an easy fix: if you first divide each vector by its length (normalising them, so that they all have length one), two vectors with the same direction are the same vector.
The fourth fails even then, as the opening example showed. The three vectors have length one, and . The detour adds up to while the direct route measures .
So is a distance in the broad sense, not a metric. The plain cosine isn't even a
distance; it's a similarity. With this vocabulary, the library names from the opening make more
sense. SciPy and pgvector are right to call a distance, in the broad sense.
scikit-learn asks for it through a parameter called metric, but there the word just means
"comparison function", not the four rules. The library that says it outright is FAISS, Meta's
library for searching among millions of vectors: its
documentation makes clear
that the cosine is a similarity, not a distance, and it doesn't even offer it as an option. To search
by cosine, you normalise the vectors and search by dot product (METRIC_INNER_PRODUCT).
Two true metrics that rank the same way
Two true metrics are hiding inside the cosine, and both appear when you normalise. If and are and divided by their lengths, their tips lie on the sphere of radius one and the cosine is simply their dot product: .
The first is the angle, . On the sphere of radius one, the angle is the length of the shortest arc between the two tips without leaving the surface, the route a plane flies between two cities. That distance does satisfy the triangle inequality: with our three vectors, . The detour through B ties with the direct route because B lies exactly halfway along it, and it can never beat it.
The second is the chord, the Euclidean distance between the normalised vectors. Its relation to the cosine takes one line: expand the square and use :
So , which is a metric because the Euclidean distance is one.
Read backwards, the same identity explains the failure from the opening:
The "cosine distance" is half the square of the Euclidean distance between the normalised vectors, and squaring breaks the triangle inequality. On a line, the points , and are separated by distances of , and ; squared, those become , and , and . Squaring penalises large distances more than small ones, so one long trip costs more than two half trips. You can see it in the numbers for small angles: , so two steps of cost each, together, while the in one go costs , twice as much.
Three ways of measuring how far apart two directions are. The arc and the chord are metrics; 1 − cos starts flat, which is why two short steps add up to less than one long one.
The important consequence is in the right-hand chart: all three measures always grow with the angle. A larger angle means a larger chord, a larger and a smaller cosine, so all three rank any list of candidates in exactly the same way. Searching for the ten closest texts by cosine, by angle or by Euclidean distance between normalised vectors gives you the same ten, in the same order. That's what OpenAI's guide says: its embeddings come normalised, so cosine and Euclidean distance produce the same ranking.
For searching, which is almost always what the cosine is used for, not being a metric doesn't matter at all. It matters when you do something with the numbers other than sort them.
When it does matter
There are three situations: when an algorithm uses the triangle inequality to save computation, when vectors get averaged, and when similarities are chained together.
Indexes that rule out candidates without looking
Some exact nearest-neighbour indexes, such as the ball tree, group the points into balls with a centre and a radius, and can rule out a whole ball with a single computation. If the query is at distance from the centre and the ball has radius , then by the triangle inequality everything inside is at least from the query. If already exceeds the best candidate found so far, the ball is skipped without looking inside. With a distance that doesn't satisfy the inequality, that bound is false and the index would throw away true neighbours.
scikit-learn knows this. Neither its BallTree nor its KDTree accepts the cosine, and when you ask
for NearestNeighbors(metric="cosine") with the automatic algorithm,
it falls back to brute force: comparing the
query with everything. The fix is the one from the previous section. Normalise the vectors and ask
for the Euclidean distance, and the tree works, with the same ordering.
Graph indexes such as HNSW (Hierarchical Navigable Small World, which many vector databases use) don't prune with the triangle inequality. They walk a graph of neighbours, always jumping to the most promising one, and they're approximate anyway. That's why hnswlib, the open-source library maintained by HNSW's first author, offers the dot product and the cosine alongside the Euclidean distance, with a warning that the dot product is not a metric.
Averaging
k-means groups points into clusters by repeating two steps: assign each point to the nearest centre, then move each centre to the mean of its points. It's built for the Euclidean distance, and averaging directions has a catch: the mean of vectors of length one doesn't have length one. Two perpendicular vectors, and , average to , which has length , and the more spread out a cluster is, the shorter its centre.
If you run plain k-means on normalised vectors, the assignment step ends up comparing each point with centres of different lengths. Since , the last term favours the clusters with the shortest centres, the most spread-out ones, for a reason that has nothing to do with resemblance. Spherical k-means (Dhillon and Modha, 2001) fixes this by normalising each centre again after averaging. The same goes for any average of embeddings: the mean of normalised vectors has to be normalised again before you compare it with anything.
Chaining
"A resembles B and B resembles C, so A resembles C." It's the reasoning of anyone who deduplicates a corpus, clusters by chains or recommends friends of friends. With a metric, the conclusion comes with a bound. With the cosine too, as long as you go through the angle, which is a metric.
Suppose and , with . Each of the two angles is at most . By the triangle inequality for angles,
The cosine decreases between and , so a larger angle gives a smaller cosine, and the double-angle formula, , finishes the calculation:
With , is guaranteed. With , it's . With , it's : nothing. A and C can be perpendicular, completely unrelated, even though each step looks fairly similar. The bound is tight, because it's reached when B lies exactly in the middle of the arc between A and C, which is what happened with our three vectors: and .
What two similarities guarantee about the third. Below 0.71 per step, nothing.
A threshold of for "similar" doesn't compose. Two hops of can join texts that have nothing to do with each other, and a clustering method that merges groups through chains (single linkage) with that threshold ends up connecting anything to anything, given enough intermediate steps.
Why the cosine won
If the cosine, the angle and the Euclidean distance between normalised vectors all rank things the same way, the question isn't why the cosine rather than the Euclidean distance. It's why we throw the length away. There are four reasons, plus a fifth that gets repeated a lot and doesn't hold up.
The legacy of information retrieval
In 1975, Salton, Wong and Yang described the vector space model for searching documents: each document is a vector with one coordinate per term, weighted by its importance (what would later be called TF-IDF, term frequency–inverse document frequency: how many times the word appears in the document, times how rare it is in the collection). On the first page they already propose comparing documents by the angle between their vectors and normalising them all to length one, placing them on the sphere.
The reason was practical. A long document repeats more words, so its vector is longer, and with the dot product long documents would win every search just for being long. The cosine removes the length, which in that setting was an accident of the text, not a property of its topic. When word2vec, the first popular word-vector model, arrived in 2013, the habit came with it: its authors already solved analogies by looking for the closest word "measured by cosine distance". Language processing inherited the measure from search engines.
Length measures something else
In word vectors, length isn't meaning. Schakel and Wilson studied it with word2vec in 2015 and found that it mixes two things: how frequent a word is and how consistent its contexts are. A word that always shows up in the same kind of sentence gets a longer vector the more often it appears. One that shows up in very different contexts, like "the" or "of", ends up with a short vector, because each context pulls it in a different direction and the pulls cancel out. They propose using length to measure how much a word matters in a corpus. That's useful information, but it isn't resemblance: with the dot product, two words would come out closer because they're important, not because they mean the same thing. The cosine asks only where each vector points.
Models are trained with the cosine
This is the strongest reason today, and it's circular in a good way: embedding models are trained with the cosine inside the loss function. Sentence-BERT (2019), the model that popularised sentence embeddings, promised in its abstract vectors that can be compared with the cosine. Contrastive training, the current standard, pulls together the pairs that should be similar and pushes the rest apart, measuring with the cosine divided by a temperature, a number that sets how sharp the contrast is: in SimCSE, a contrastive method from 2021. Wang and Isola (2020) formalised the idea: the vectors are placed on the sphere of radius one and training pursues two goals, alignment (similar pairs together) and uniformity (everything else spread over the whole sphere).
A model trained like this never receives any signal about length, because the loss doesn't see it. Length is noise, and many models remove it themselves: OpenAI's embeddings come out already normalised. With them, the cosine, the dot product and the Euclidean distance are interchangeable, and the dot product is the cheapest. The general rule is that the right measure is the one the model was trained with.
It's cheap
You normalise once, at indexing time, and from then on each cosine is a dot product: multiplications and additions. Comparing a query with a million documents is a single matrix-vector product, which is what graphics cards and linear algebra libraries do best. And since the result lies between and , the vectors compress well, for example to 8-bit integers.
The angle has its own shortcut, too. Charikar showed in 2002 that if you cut space with a random plane through the origin, the probability that two vectors fall on different sides is . With 256 random planes, each vector becomes 256 bits, and the fraction of bits in which two vectors differ estimates their angle divided by . The technique is called SimHash, and it estimates the angle, which is a metric, not .
What doesn't explain it: the curse of dimensionality
A common explanation is that in many dimensions the Euclidean distance loses its meaning while the cosine doesn't. The first half has a basis: Beyer and colleagues proved in 1999 that, under fairly general conditions, as the dimension grows the point nearest to a query and the farthest one end up at almost the same distance. The second half can't be true for normalised vectors: if the cosine and the Euclidean distance rank things the same way, they suffer equally.
The cosine concentrates too. Between two random directions in dimensions, the cosine has mean and standard deviation . In 768 dimensions that's , so almost every pair of random vectors is almost perpendicular. What saves embeddings isn't the measure but the fact that their points aren't random: they're crowded into a small, structured part of the space.
So the real choice is whether to keep the length or throw it away. In almost all text embeddings, the length is noise (the model never learnt to use it) or measures something we don't want to compare (how frequent or important a word is, how long a document is). That's why we use the cosine.
The other measures
The table summarises the ones that appear in language processing, what they are and whether they see length.
| measure | what it is | sees length? | where it appears |
|---|---|---|---|
| cosine | similarity, from to | no | almost every text embedding model |
| angle, | metric | no | SimHash; when a true metric is needed |
| dot product | unbounded similarity | yes | DPR, recommender systems |
| Euclidean | metric | yes, except between normalised vectors | tree indexes, k-means |
| Manhattan | metric: sum of absolute differences | yes | rarely with embeddings |
| Mahalanobis | metric that discounts the correlations between coordinates | yes | whitening embeddings |
| Pearson | similarity, from to | no | the cosine after subtracting each vector's mean coordinate |
| Jaccard | is a metric; compares sets | n/a | deduplicating corpora (with MinHash) |
| Hamming | metric: counts differing bits | n/a | binary codes, SimHash |
| Jensen–Shannon | divergence between distributions; its square root is a metric | n/a | comparing word or topic distributions |
| cross-encoder | learnt, no geometry | n/a | reranking results |
Three of them deserve a paragraph.
The dot product is the one that keeps the length, and it's the right choice when length is information. In a recommender system, the dot product of a user's vector and an item's vector is the prediction, and the length of an item's vector tends to capture how popular it is, which is a good reason to recommend it. DPR (Dense Passage Retrieval, 2020), a passage retriever for answering questions, was trained with the dot product, and in its own tests the Euclidean distance performed similarly and both beat the cosine, though with settings tuned for the dot product. It isn't even a well-behaved similarity, though: a vector can resemble another more than it resembles itself. With and , the product of the first with itself is and with the second is .
The Mahalanobis distance is the Euclidean distance after whitening the data: transforming it so that the coordinates are uncorrelated and all have the same variance. It's the link to the fix in the next section.
Cross-encoders play a different game. All the measures above compare two vectors computed separately, with each text encoded on its own. A cross-encoder reads both texts at once and returns a score, so it sees every word of one against every word of the other, and it's usually more accurate. The price is that nothing can be computed in advance: each pair requires a full pass through the model. That's why the usual pattern is to use the cosine to pull a hundred candidates out of millions and the cross-encoder to rerank those hundred. The cosine isn't the best similarity there is. It's the best one that fits in an index.
Where the cosine falls short
First, a distinction that saves arguments: a failure of the measure is not the same as a failure of the representation. "Hot" and "cold" have a high cosine in many word models, and so do a sentence and its negation. That isn't the cosine's fault. Those words appear in the same contexts, the model placed them close together, and the cosine faithfully reports what the model learnt. No measure can fix a representation that doesn't tell two things apart; that gets fixed in training.
Three failures do belong to the measure.
When everything points the same way
In 2019, Ethayarajh measured the average cosine between randomly chosen words inside language models such as BERT (Google, 2018) and GPT-2 (OpenAI, 2019), using the vector each layer of the model assigns to each word. In GPT-2 it was around in layers 2 to 8, and in the last layer almost : any two words had an almost perfect cosine. In BERT's last layer it was around . This is called anisotropy: the vectors don't fill the whole sphere but a narrow cone, and everything resembles everything.
Timkey and van Schijndel found part of the cause in 2021: a few rogue dimensions with huge values. In BERT's layer 11, a single coordinate out of 768 contributes 88% of the expected cosine between two vectors; in XLNet, another 2019 model, 99.6%. In those cases the cosine is measuring a single coordinate.
This happens above all when you take vectors from a language model that wasn't trained to compare them. The fixes, from cheapest to most expensive: centring (subtracting the collection's mean from every vector; Mu and Viswanath also remove the few dominant directions), standardising each coordinate, which is Timkey and van Schijndel's fix, whitening (which amounts to comparing with the Mahalanobis distance), or using a model trained with a contrastive loss, whose uniformity pushes directly against the cone.
Even good models have their own scale. The model card for E5, a family of embedding models, warns that its cosines usually fall between and because of its training temperature (), and that what matters is the relative order. A cosine of doesn't mean "80% similar", and a threshold chosen for one model doesn't work for another: it has to be calibrated with labelled pairs from your own data.
When the length was the signal
In 2024, Steck, Ekanadham and Kallus, from Netflix, published a paper whose title is a question: Is Cosine-Similarity of Embeddings Really About Similarity? In a family of linear recommendation models, the prediction is the product of two matrices, , and you can multiply each column of by any factor as long as you divide the matching column of by the same factor. With a diagonal matrix :
The predictions don't change, but the cosines between the rows of do. The model doesn't determine them, and depending on the training they can come out arbitrary. The authors' recipe: if you're going to compare with the cosine, train with the cosine inside the loss. Otherwise, the only thing the model pinned down is the dot product. It's the principle from before, seen from the side where it fails.
When the relation has a direction
The cosine is symmetric: that's the third rule, the one it does satisfy. Many relations aren't. A question and its answer aren't interchangeable. A dog is an animal, but not the other way round. One sentence can imply another without the second implying the first.
There are three ways out. The first is to put the asymmetry in the model instead of the measure: E5
asks you to prefix questions with query: and documents with passage: , so the same text is
encoded differently depending on its role. The second is to change the geometry:
order embeddings represent "is a" as an order between vectors,
and hyperbolic embeddings place hierarchies in a space where trees
fit without being squeezed. The third is to compare piece by piece: ColBERT,
a retriever from 2020, stores one normalised vector per word and scores by adding up, for each word
of the question, its best cosine with any word of the document. That sum runs over the question and
not the document, so it's asymmetric by construction. And there's always the cross-encoder.
What to take away
If you remember only one thing, make it this: the cosine is a similarity, and is a distance that isn't a metric, because it's half the square of the Euclidean distance between the normalised vectors. For searching, it makes no difference, because the angle, the chord and the cosine rank things in exactly the same way. For averaging, chaining or pruning an index it does, and the metric to use is the angle or the Euclidean distance between normalised vectors.
And if you remember a second thing: the cosine didn't win because it measures meaning better. It won because it throws the length away, which in almost all text embeddings is either noise or a measure of something else, and because models are trained with it inside the loss.
The rest is practical.
Use the measure the model was trained with. It's usually on the model card. If it's the cosine and the vectors already come normalised, use the dot product: same order, fewer operations.
If the length means something, don't throw it away. Popularity, frequency, importance: if the model was trained with the dot product, compare with the dot product.
Don't set thresholds by eye. A cosine of means something different in each model, and two similarities of don't guarantee a third. Calibrate with labelled pairs and, if you take vectors from a model that wasn't trained for comparison, centre them first.
For relations with a direction, put the asymmetry somewhere else. Use different prefixes for questions and documents, or a cross-encoder that reranks the top results.