# Euclidean distance

> Source: https://aiwiki.ai/wiki/euclidean_distance
> Updated: 2026-11-18
> Fact-checked: 2026-11-18
> Categories: Information Retrieval, Machine Learning, Mathematics
> License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/) - attribute to "AI Wiki (aiwiki.ai)"
> Cite as: AI Wiki. "Euclidean distance." aiwiki.ai, 18 Nov 2026. https://aiwiki.ai/wiki/euclidean_distance
> From AI Wiki (https://aiwiki.ai), the free encyclopedia of artificial intelligence. Reuse freely with attribution.

**Euclidean distance** is the length of the straight line segment between two points, computed by taking the difference between the points in each coordinate, squaring those differences, adding them up and taking the square root [1][2]. It is the distance induced by the Euclidean norm, also called the $\ell_2$ norm, so it is often written $\lVert x - y \rVert_2$ and called the L2 distance [3]. In [machine learning](https://aiwiki.ai/wiki/machine_learning) it is the default distance of the [k-nearest neighbors](https://aiwiki.ai/wiki/k_nearest_neighbors) classifier in [scikit-learn](https://aiwiki.ai/wiki/scikit_learn) [12], its square is the quantity that [k-means](https://aiwiki.ai/wiki/k-means) clustering minimizes [15], and it is one of the standard metrics offered by vector search libraries and [vector databases](https://aiwiki.ai/wiki/vector_database) such as [FAISS](https://aiwiki.ai/wiki/faiss), [pgvector](https://aiwiki.ai/wiki/pgvector), [Milvus](https://aiwiki.ai/wiki/milvus) and [Weaviate](https://aiwiki.ai/wiki/weaviate) [6][7][8][19]. Its main alternative for comparing [embeddings](https://aiwiki.ai/wiki/embeddings) is [cosine similarity](https://aiwiki.ai/wiki/cosine_similarity), which looks only at the angle between vectors; for vectors normalized to unit length the two produce the same ranking of nearest neighbors [6][20].

<figure>
<img src="/images/media-2026-11-18-euclidean_distance-4eba253e99df.png" alt="Graph of points p and q joined by a line, with horizontal and vertical legs forming a right triangle" width="1200" height="826" />
<figcaption>The Euclidean distance d(p, q) between two points in the plane is the hypotenuse of a right triangle whose legs are the coordinate differences q1 - p1 and q2 - p2. Kmhkmh, via <a href="https://commons.wikimedia.org/wiki/File:Euclidean_distance_2d.svg">Wikimedia Commons</a>, <a href="https://creativecommons.org/licenses/by/4.0">CC BY 4.0</a>.</figcaption>
</figure>

## Definition

For two points $p = (p_1, \ldots, p_n)$ and $q = (q_1, \ldots, q_n)$ in $n$-dimensional real space, the Euclidean distance is [1][2]:

$$
d(p, q) = \sqrt{\sum_{i=1}^{n} (p_i - q_i)^2}
$$

where $p_i$ and $q_i$ are the coordinates of the two points in dimension $i$. In the plane, with $p = (x_1, y_1)$ and $q = (x_2, y_2)$, this reduces to $\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}$ [1], which is the length given by the Pythagorean theorem [2]. For example, the points $(1, 2)$ and $(4, 6)$ differ by 3 in the first coordinate and 4 in the second, so their distance is $\sqrt{9 + 16} = 5$.

In vector notation the distance is the norm of the difference vector. The Euclidean norm of a vector $x \in \mathbb{R}^n$ is

$$
\lVert x \rVert_2 = \sqrt{\sum_{i=1}^{n} x_i^2} = \sqrt{x^\top x}
$$

and it gives the Euclidean distance of $x$ from the origin [3]. The textbook *Mathematics for Machine Learning* defines the distance between two vectors in an inner product space as $d(x, y) = \lVert x - y \rVert = \sqrt{\langle x - y, x - y \rangle}$ and calls it the Euclidean distance when the inner product is the ordinary [dot product](https://aiwiki.ai/wiki/dot_product) [3]. MathWorld describes the $\ell_2$ norm as also known as the Euclidean norm, while noting that it does not recommend that name because it can be confused with the Frobenius norm of a matrix [4].

### Weighted and standardized forms

SciPy's `scipy.spatial.distance.euclidean` function accepts an optional weight vector $w$ and computes $\left(\sum_i w_i (u_i - v_i)^2\right)^{1/2}$, with every weight equal to 1.0 by default [5]. The standardized Euclidean distance divides each squared difference by the variance of that component, $\sqrt{\sum_i (u_i - v_i)^2 / V_i}$, where $V$ is a vector of per-component variances usually computed over a larger collection of points [21].

## Mathematical properties

### Metric axioms

Euclidean distance is a metric in the mathematical sense. A metric $d$ is positive definite ($d(x, y) \ge 0$, with $d(x, y) = 0$ exactly when $x = y$), symmetric ($d(x, y) = d(y, x)$), and satisfies the triangle inequality $d(x, z) \le d(x, y) + d(y, z)$; *Mathematics for Machine Learning* presents the Euclidean distance as a special case of a metric [3]. These properties matter in practice: scikit-learn's documentation notes that a user-defined distance must be a true metric, satisfying non-negativity, identity, symmetry and the triangle inequality, before it can be used inside its BallTree index [11].

### Squared Euclidean distance

Many algorithms work with the squared distance $\lVert x - y \rVert_2^2 = \sum_i (x_i - y_i)^2$ instead of the distance itself. The squared form is not a metric, because it can violate the triangle inequality. Three points on a line at 0, 1 and 2 show this: the squared distances from 0 to 1 and from 1 to 2 are both 1, but the squared distance from 0 to 2 is 4, which is larger than $1 + 1$.

Squaring is still useful because the square root is an increasing function, so dropping it never changes which point is nearest. Several search libraries therefore report squared values when asked for L2 distance. The FAISS wiki states that FAISS "reports squared Euclidean (L2) distance, avoiding the square root", and that a square root must be applied to the result if exact distances are needed [6]. Milvus documents that it calculates only the value before the square root is applied when Euclidean distance is chosen [7]. Weaviate names its metric `l2-squared` and defines it as $\sum_i (a_i - b_i)^2$ [8], and the hnswlib library's `'l2'` space is likewise the squared L2 distance [9].

### Expansion in terms of dot products

The squared distance expands into norms and a dot product:

$$
\lVert x - y \rVert_2^2 = x^\top x - 2\, x^\top y + y^\top y
$$

scikit-learn's `euclidean_distances` function computes distances this way, as `sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))`. Its documentation gives two reasons: the form is computationally efficient for sparse data, and the squared norms `dot(x, x)` and `dot(y, y)` can be precomputed when one argument stays fixed [10]. The same page warns that this is not the most precise way to compute the distance, because the subtraction can suffer from catastrophic cancellation, and that the returned distance matrix may not be exactly symmetric [10].

The expansion also shows how Euclidean distance relates to the dot product and to cosine similarity. When both vectors have unit length, $x^\top x = y^\top y = 1$, so $\lVert x - y \rVert_2^2 = 2 - 2\langle x, y \rangle$, an identity stated in the FAISS documentation [6]. Since the dot product of two unit vectors is the cosine of the angle $\theta$ between them, the squared distance between unit vectors equals $2(1 - \cos\theta)$.

### Related distances

Euclidean distance is one member of several larger families:

| Distance | Formula | Relation to Euclidean distance |
|---|---|---|
| Euclidean (L2) | $\sqrt{\sum_i (x_i - y_i)^2}$ | Itself |
| Manhattan (L1) | $\sum_i \lvert x_i - y_i \rvert$ | Minkowski distance with $p = 1$ |
| Minkowski ($L_p$) | $\left(\sum_i \lvert x_i - y_i \rvert^p\right)^{1/p}$ | Equals Euclidean distance when $p = 2$ |
| Chebyshev | $\max_i \lvert x_i - y_i \rvert$ | Largest single coordinate difference |
| Standardized Euclidean | $\sqrt{\sum_i (x_i - y_i)^2 / V_i}$ | Euclidean distance after dividing each coordinate difference by its standard deviation |
| Mahalanobis | $\sqrt{(x - y)^\top V^{-1} (x - y)}$ | Equals Euclidean distance when $V$ is the identity matrix |

The formulas follow scikit-learn's `DistanceMetric` documentation [11]. The `KNeighborsClassifier` documentation states that its Minkowski power parameter gives Manhattan distance for $p = 1$ and Euclidean distance for $p = 2$ [12]. In the Mahalanobis distance, $V$ is the covariance matrix [27]; setting it to the identity removes the matrix and leaves the plain Euclidean formula.

## Uses in machine learning

### Nearest-neighbor methods

The k-nearest neighbors algorithm classifies a point by looking at the training points closest to it, so the choice of distance defines what "close" means. In scikit-learn, `KNeighborsClassifier` defaults to `n_neighbors=5`, `metric='minkowski'` and `p=2`, which the documentation describes as resulting in "the standard Euclidean distance" [12]. The library's nearest-neighbor guide lists `euclidean` among the metrics its KD tree supports, and it describes a `NearestCentroid` classifier that represents each class by the centroid of its members [13].

Because every coordinate contributes its squared difference to the total, Euclidean distance is sensitive to the units of each feature. scikit-learn's "Importance of Feature Scaling" example shows a k-nearest neighbors model on a wine dataset in which the feature "proline" ranges up to about 1,000 while "hue" varies between 1 and 10; without scaling, the distances between samples are mostly determined by proline and hue is comparatively ignored [14]. After standardization with `StandardScaler`, both features lie roughly between -3 and 3 and influence the neighbor structure about equally [14]. The same page describes this kind of standardization as [z-score normalization](https://aiwiki.ai/wiki/z-score_normalization) and notes that many algorithms other than tree-based models require features to be normalized [14].

### k-means clustering and centroids

The k-means algorithm is built on squared Euclidean distance. scikit-learn describes it as separating samples into groups of equal variance by minimizing the inertia, or within-cluster sum of squares [15]:

$$
\sum_{i=0}^{n-1} \min_{\mu_j \in C} \lVert x_i - \mu_j \rVert^2
$$

where $C$ is the set of cluster centers $\mu_j$. In the usual procedure, often called Lloyd's algorithm, each sample is assigned to its nearest centroid and each centroid is then replaced by the mean of the samples assigned to it, and the two steps repeat [15]. scikit-learn notes that these means, commonly called the cluster "centroids", are not in general points from the data set, although they live in the same space [15]. See [centroid](https://aiwiki.ai/wiki/centroid) for the geometry of the mean.

The scikit-learn documentation lists drawbacks that follow from this geometry. Inertia assumes clusters are convex and isotropic, so it responds poorly to elongated clusters or irregularly shaped manifolds [15]. In very high-dimensional spaces Euclidean distances tend to become inflated, and the documentation suggests running a dimensionality reduction method such as [principal component analysis](https://aiwiki.ai/wiki/principal_component_analysis) before k-means [15].

### Least squares and PCA

Squared Euclidean distance is also the error measure behind least-squares fitting. *Mathematics for Machine Learning* notes that in [linear regression](https://aiwiki.ai/wiki/linear_regression) the sum of squared errors between the observations $y$ and the predictions $X\theta$ equals the squared Euclidean distance $\lVert y - X\theta \rVert^2$ [3]. The same book derives principal component analysis as the projection that minimizes the average squared Euclidean distance between each data point and its reconstruction, the reconstruction error [3].

### Kernels

The radial basis function (RBF) kernel, the default kernel of scikit-learn's `SVC` [support vector machine](https://aiwiki.ai/wiki/support_vector_machine_svm) classifier [28], is a function of squared Euclidean distance. scikit-learn's `rbf_kernel` function defines it as $K(x, y) = \exp(-\gamma \lVert x - y \rVert^2)$, with $\gamma$ set to one divided by the number of features when no value is given [16]; `SVC` itself defaults to `gamma='scale'` [28]. The kernel value is 1 for identical points and decays toward 0 as the distance grows.

### Learned embedding spaces

Some deep learning systems train a network so that Euclidean distance in its output space carries meaning directly. FaceNet, by Schroff, Kalenichenko and Philbin of Google and presented at CVPR 2015, learns a mapping from face images to a compact Euclidean space in which distances correspond to face similarity [17]. Its embeddings are constrained to lie on a hypersphere ($\lVert f(x) \rVert_2 = 1$), and it trains with a triplet loss that pushes the squared L2 distance between an anchor image and a different image of the same person to be smaller, by a margin $\alpha$, than the squared distance between the anchor and an image of another person [17]. Face verification then thresholds the squared L2 distance between two embeddings. The system reached 99.63% accuracy on the Labeled Faces in the Wild benchmark while using 128 bytes per face [17].

Prototypical networks, introduced by Snell, Swersky and Zemel in 2017 for [few-shot learning](https://aiwiki.ai/wiki/few-shot_learning), classify a query by its distance to a prototype for each class, the mean of that class's embedded support examples [18]. The authors focus on squared Euclidean distance, which is a Bregman divergence, and report that the choice of distance is "vital": Euclidean distance greatly outperformed the more commonly used cosine similarity, and squared Euclidean distance also improved results for matching networks, which earlier work had applied with cosine distance [18]. They also show that with squared Euclidean distance the classifier is equivalent to a linear model on the embeddings, with weights $w_k = 2c_k$ and bias $b_k = -c_k^\top c_k$ for class prototype $c_k$, and they conjecture that cosine distance performs worse because it is not a Bregman divergence [18].

### Vector search

Nearest-neighbor search over embeddings, as used in [semantic search](https://aiwiki.ai/wiki/semantic_search) and [retrieval-augmented generation](https://aiwiki.ai/wiki/retrieval_augmented_generation), commonly supports Euclidean distance alongside inner product and cosine measures:

| System | Euclidean option | Notes |
|---|---|---|
| [FAISS](https://aiwiki.ai/wiki/faiss) | `METRIC_L2`, `IndexFlatL2` | Reports squared L2 distance; `IndexFlatL2` is brute-force L2 search [6][22] |
| [pgvector](https://aiwiki.ai/wiki/pgvector) | `<->` operator, `vector_l2_ops` | Also offers inner product (`<#>`), cosine (`<=>`) and L1 (`<+>`) [19] |
| [Milvus](https://aiwiki.ai/wiki/milvus) | `L2` | Computes the value before the square root [7] |
| [Weaviate](https://aiwiki.ai/wiki/weaviate) | `l2-squared` | Default metric is cosine [8] |
| hnswlib | `'l2'` | Squared L2; also `'ip'` and `'cosine'` [9] |

hnswlib, a library implementing the [HNSW](https://aiwiki.ai/wiki/hnsw) graph index for [approximate nearest neighbor search](https://aiwiki.ai/wiki/approximate_nearest_neighbor_search), supports all three measures [9]. pgvector's documentation recommends the inner product operator for vectors normalized to length 1, such as OpenAI embeddings, for the best performance [19].

## Comparison with cosine similarity

Cosine similarity measures only the angle between two vectors, while Euclidean distance measures how far apart their endpoints are, so it depends on both direction and length. Pinecone's guide to vector similarity describes Euclidean distance as "sensitive to scale as well as the vectors' relative location in space" and suggests it suits embeddings that encode counts or measures of things, giving the example of a recommender comparing how many times items were purchased [23].

| Property | Euclidean distance | Cosine similarity |
|---|---|---|
| What it measures | Straight-line distance between points | Cosine of the angle between vectors |
| Sensitive to vector length | Yes | No |
| Direction of "more similar" | Smaller is more similar | Larger is more similar |
| Range | 0 to infinity | -1 to 1 |

The two measures agree once vectors are normalized. For unit vectors the squared Euclidean distance is $2 - 2\cos\theta$ [6], a decreasing function of cosine similarity, so sorting neighbors by smallest Euclidean distance gives the same order as sorting by largest cosine similarity. OpenAI's embeddings guide makes this point for its own models: the embeddings are normalized to length 1, so cosine similarity and Euclidean distance "will result in the identical rankings", and the company recommends cosine similarity while noting that the choice of distance function typically does not matter much [20]. FAISS uses the same relationship in the other direction: to search by cosine similarity, it normalizes database and query vectors and runs an inner product search, which it notes is equivalent to an L2 index apart from the distance values reported [6]. Without normalization the measures can disagree: Milvus's documentation answers the question of why L2 and inner product searches return different results by telling users to check whether their vectors are normalized [7].

Which measure works better depends on how the embedding was trained. Prototypical networks found squared Euclidean distance clearly better than cosine for few-shot image classification [18], while OpenAI recommends cosine similarity for its normalized text embeddings [20]. In a 2024 paper in the companion proceedings of the ACM Web Conference, Steck, Ekanadham and Kallus observed that cosine similarity of learned embeddings sometimes works better and sometimes worse than the unnormalized dot product; analyzing embeddings from regularized linear models, they derived how cosine similarity can yield arbitrary and therefore meaningless similarities, in some models implicitly controlled by the regularization, and cautioned against using it blindly [24].

## Behavior in high dimensions

Beyer, Goldstein, Ramakrishnan and Shaft showed in 1999 that under a broad set of conditions, as dimensionality increases, the distance from a query to its nearest data point approaches the distance to its farthest data point, and their experiments on real and synthetic data showed that the effect can occur with as few as 10 to 15 dimensions [25]. They stressed that this does not make high-dimensional nearest-neighbor search meaningless for every workload, and identified workloads where the effect does not occur [25].

Aggarwal, Hinneburg and Keim followed in 2001 by examining $L_k$ norms directly. They found that how meaningful distances remain in high dimensions depends on $k$, concluding that the Manhattan ($L_1$) distance is consistently preferable to the Euclidean ($L_2$) distance for high-dimensional data mining, and that an extension to fractional distance metrics can significantly improve the effectiveness of clustering algorithms such as k-means [26].

The same issue shows up in software. scikit-learn notes that its KD tree is very fast for searches in fewer than about 20 dimensions but becomes inefficient as the dimension grows, which it calls one manifestation of the "curse of dimensionality"; for larger dimensions a query can be slower than brute force [13]. See [curse of dimensionality](https://aiwiki.ai/wiki/curse_of_dimensionality) for the broader phenomenon.

## See also

- [Cosine similarity](https://aiwiki.ai/wiki/cosine_similarity)
- [Similarity measure](https://aiwiki.ai/wiki/similarity_measure)
- [Metric](https://aiwiki.ai/wiki/metric)
- [k-nearest neighbors](https://aiwiki.ai/wiki/k_nearest_neighbors)
- [k-means](https://aiwiki.ai/wiki/k-means)
- [Embedding vector](https://aiwiki.ai/wiki/embedding_vector)
- [Earth mover's distance](https://aiwiki.ai/wiki/earth_mover_s_distance)

## References

1. Black, Paul E. "Euclidean distance". Dictionary of Algorithms and Data Structures, NIST, 17 December 2004. https://xlinux.nist.gov/dads/HTML/euclidndstnc.html
2. Weisstein, Eric W. "Distance". MathWorld, Wolfram Research. https://mathworld.wolfram.com/Distance.html
3. Deisenroth, Marc Peter; Faisal, A. Aldo; Ong, Cheng Soon. "Mathematics for Machine Learning". Cambridge University Press, 2020. https://mml-book.github.io/book/mml-book.pdf
4. Weisstein, Eric W. "L^2-Norm". MathWorld, Wolfram Research. https://mathworld.wolfram.com/L2-Norm.html
5. SciPy. "scipy.spatial.distance.euclidean". SciPy v1.18.0 Manual. https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.euclidean.html
6. Meta (facebookresearch). "MetricType and distances". Faiss wiki, GitHub. https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances
7. Milvus. "Similarity Metrics". Milvus Documentation. https://milvus.io/docs/metric.md
8. Weaviate. "Distance metrics". Weaviate Documentation. https://docs.weaviate.io/weaviate/config-refs/distances
9. nmslib. "hnswlib: Header-only C++/python library for fast approximate nearest neighbors". GitHub. https://github.com/nmslib/hnswlib
10. scikit-learn developers. "euclidean_distances". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.euclidean_distances.html
11. scikit-learn developers. "DistanceMetric". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.DistanceMetric.html
12. scikit-learn developers. "KNeighborsClassifier". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html
13. scikit-learn developers. "1.6. Nearest Neighbors". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/neighbors.html
14. scikit-learn developers. "Importance of Feature Scaling". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/auto_examples/preprocessing/plot_scaling_importance.html
15. scikit-learn developers. "2.3. Clustering". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/clustering.html
16. scikit-learn developers. "rbf_kernel". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.rbf_kernel.html
17. Schroff, Florian; Kalenichenko, Dmitry; Philbin, James. "FaceNet: A Unified Embedding for Face Recognition and Clustering". IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2015. arXiv:1503.03832. https://arxiv.org/abs/1503.03832
18. Snell, Jake; Swersky, Kevin; Zemel, Richard S. "Prototypical Networks for Few-shot Learning". Advances in Neural Information Processing Systems 30 (NIPS 2017). arXiv:1703.05175. https://arxiv.org/abs/1703.05175
19. pgvector. "pgvector: Open-source vector similarity search for Postgres". GitHub. https://github.com/pgvector/pgvector
20. OpenAI. "Vector embeddings". OpenAI API documentation. https://developers.openai.com/api/docs/guides/embeddings
21. SciPy. "scipy.spatial.distance.seuclidean". SciPy v1.18.0 Manual. https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.seuclidean.html
22. Meta (facebookresearch). "Getting started". Faiss wiki, GitHub. https://github.com/facebookresearch/faiss/wiki/Getting-started
23. Schwaber-Cohen, Roie. "Vector Similarity Explained". Pinecone, 30 June 2023. https://www.pinecone.io/learn/vector-similarity/
24. Steck, Harald; Ekanadham, Chaitanya; Kallus, Nathan. "Is Cosine-Similarity of Embeddings Really About Similarity?". Companion Proceedings of the ACM Web Conference 2024 (WWW '24 Companion), pp. 887-890. doi:10.1145/3589335.3651526. arXiv:2403.05440. https://arxiv.org/abs/2403.05440
25. Beyer, Kevin; Goldstein, Jonathan; Ramakrishnan, Raghu; Shaft, Uri. "When Is 'Nearest Neighbor' Meaningful?". Database Theory, ICDT'99, Lecture Notes in Computer Science 1540, pp. 217-235, Springer, 1999. https://doi.org/10.1007/3-540-49257-7_15
26. Aggarwal, Charu C.; Hinneburg, Alexander; Keim, Daniel A. "On the Surprising Behavior of Distance Metrics in High Dimensional Space". Database Theory, ICDT 2001, Lecture Notes in Computer Science, pp. 420-434, Springer, 2001. https://doi.org/10.1007/3-540-44503-x_27
27. SciPy. "scipy.spatial.distance.mahalanobis". SciPy v1.18.0 Manual. https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.mahalanobis.html
28. scikit-learn developers. "SVC". scikit-learn 1.9.1 documentation. https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html

