Distance measures
Formulas for the distance measures used in data science: Manhattan, Euclidean, Minkowski, Chebyshev, cosine, Hamming and Jaccard.
2 min readUpdated
Many machine learning methods, such as k-nearest neighbours, k-means clustering and similarity search over embeddings, decide how alike two data points are by computing a distance between them. The choice of distance changes the result, so it should fit the data: real-valued coordinates, high-dimensional vectors, binary strings or sets.
The overview below shows thirteen common measures. This note gives the formulas for the ones used most often. In all of them, and are vectors in .

Manhattan distance
The sum of the absolute differences of the coordinates: the distance travelled along a grid, like a taxi in a city with rectangular blocks. It is less sensitive to a single large difference than the Euclidean distance.
Euclidean distance
The length of the straight line between the two points. It is the default for low-dimensional, real-valued data, and works best when all features are on the same scale, so normalise them first.
Minkowski distance
A generalisation of the Manhattan and Euclidean distances. It adds a parameter , called the order, that selects the measure:
is a real number with ; below 1 the result is no longer a metric. Special cases:
- Manhattan distance
- Euclidean distance
- Chebyshev distance
Chebyshev distance
The largest difference along any single coordinate, the limit of the Minkowski distance as grows. It counts the moves of a king on a chessboard.
Cosine distance
Compares the direction of two vectors and ignores their length. It suits high-dimensional data such as text embeddings or word counts, where the length mostly reflects document size. Cosine similarity is the cosine of the angle between the vectors, and the distance is one minus the similarity:
Hamming distance
The number of positions at which two strings or vectors of equal length differ. It is used for binary codes, categorical features and error detection.
is 1 when the values differ and 0 when they are equal.
Jaccard distance
Compares two sets and : the size of the intersection divided by the size of the union is the Jaccard index, and the distance is one minus the index. It suits sets of tags, words or items bought.