AI Engineer Roadmap All lessons Interactive Quiz GitHub

Euclidean Distance

Beginner · 6 min read · Updated · By Saurabh Pathak

In short: Euclidean distance is the straight-line distance between two points, so smaller means more similar and 0 means identical.

Play the interactive lesson: Euclidean distanceRead on GitHub
On this page
  1. Explain it like I'm new
  2. Watch it
  3. How it works
  4. Code example
  5. When to use it / when not to
  6. Common mistakes
  7. Recap
  8. Interview questions
  9. Go deeper

Level: Beginner · Reading time: 6 min · Phase: 1 — RAG Foundations

Before you start: Embeddings and Cosine Similarity. You should know that an embedding is a vector (a list of numbers) and that cosine compares direction.

Explain it like I'm new

Put two pins on a paper map and stretch a ruler between them. The ruler reading is the Euclidean distance. It is the "as the crow flies" distance you learned with Pythagoras: for a right triangle with sides 3 and 4, the long side is 5.

An embedding is a point in a space with many dimensions. The same ruler idea works in 384 or 1,536 dimensions; you just add more squared terms.

Words to know:

Unlike cosine similarity, Euclidean distance cares about length too. Two vectors that point the same way but have different lengths are "far apart" by Euclidean distance, yet "identical" by cosine. It is also called the L2 distance (after the L2 norm). Vector databases and FAISS often call it L2.

Watch it

Euclidean distance: The straight-line distance between two points. A worked example.
Euclidean distance: The straight-line distance between two points. A worked example.

It plays on a loop. Read the caption in the box, one step at a time. Want to go at your own pace? Step through it with Previous and Next.

How it works

  1. Subtract the vectors element by element.
  2. Square each difference.
  3. Add them up.
  4. Take the square root: d(a, b) = √((a₁−b₁)² + (a₂−b₂)² + …).
y
4 |        * b (3,4)
3 |       /
2 |      /  d = 5
1 |     /
0 *----+----+----+-- x
  a (0,0)

Worked examples:

Worked example

A query q = [0, 0] is compared with three stored vectors [3, 4], [1, 1] and [0, 2].

  1. [3, 4]: squares 9 + 16 = 25, distance √25 = 5.
  2. [1, 1]: squares 1 + 1 = 2, distance √2 ≈ 1.414.
  3. [0, 2]: squares 0 + 4 = 4, distance √4 = 2.
  4. Smaller is closer, so the order is [1, 1], [0, 2], [3, 4].

If you used squared distance (2, 4, 25) the order would be the same, which is why libraries skip the square root.

Squared distance: many libraries skip the square root. Ranking is the same (the square root keeps order), and it is cheaper.

The useful identity. For unit-length vectors u and v: ‖u − v‖² = 2 − 2·cos(u, v). So on normalized embeddings, ranking by smallest Euclidean distance gives exactly the same order as ranking by highest cosine similarity. code/rag_vector_math.py checks this in its tests.

Code example

From code/rag_vector_math.py:

import math

def euclidean_distance(a, b):
    if len(a) != len(b):
        raise ValueError("vectors must have the same length")
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

def normalize(a):
    n = math.sqrt(sum(x * x for x in a))
    return [x / n for x in a]

print(euclidean_distance([0, 0], [3, 4]))              # 5.0
print(euclidean_distance([1, 2, 3], [2, 4, 6]))        # 3.741...
u, v = normalize([1, 2, 3]), normalize([2, 4, 6])
print(euclidean_distance(u, v))                        # 0.0: same point after normalizing

In real projects (FAISS, pip install faiss-cpu numpy):

import faiss
import numpy as np

xb = np.random.rand(10_000, 128).astype("float32")     # stored vectors
xq = np.random.rand(5, 128).astype("float32")          # queries
index = faiss.IndexFlatL2(128)                         # exact search, squared L2
index.add(xb)
distances, ids = index.search(xq, 4)                   # 4 nearest per query

When to use it / when not to

MetricHigher or lower is better?Sensitive to length?
Cosine similarityHigherNo
Dot productHigherYes
Euclidean (L2)LowerYes

Common mistakes

Recap

If you remember only three things:

Interview questions

1. How do Euclidean distance and cosine similarity differ? <details><summary>Answer</summary> Euclidean measures straight-line distance and depends on vector length; cosine measures only the angle. Two vectors in the same direction but with different lengths have cosine 1 but a non-zero Euclidean distance. </details>

2. When do they produce the same ranking? <details><summary>Answer</summary> When all vectors are normalized to length 1, because then squared Euclidean distance equals 2 − 2·cosine, a decreasing function of cosine. </details>

3. Why do libraries often use squared L2? <details><summary>Answer</summary> The square root does not change the order of results and costs extra compute, so skipping it is faster with the same ranking. </details>

Go deeper

Prev: Cosine Similarity · Next: Dot Product · Back to phase: Phase 1