Skip to main content

Distance, from the plane to many dimensions

The two changes between two points are the legs of a right triangle, so Pythagoras gives the straight-line distance. Measure it in the plane, in space and for lists of any length, find a nearest neighbour by hand, and code it from scratch and with math.dist.
M01.2.3L0 Foundation25 minIn review

Before this lesson

M01.2.1 The coordinate plane M01.2.2 Right triangles and Pythagoras' theorem

After this lesson you can

  • Derive the distance formula in the plane from the two changes between the points and Pythagoras’ theorem.
  • Compute the distance between two points in the plane and in space, and explain why the order of subtraction does not matter.
  • Extend the distance formula to points with any number of coordinates, such as two rows of a data table.
  • Find which of several points is nearest to a new point by computing every distance.

In review. The maths and code on this page are checked by automated tests on every change, but an independent reader has not signed it off yet. Spot a mistake or a confusing step? Tell us.

The question

A new example arrives at the point \((3, 3)\). Four examples are already stored: the course’s data points \((1, 2)\), \((2, 3)\), \((3, 5)\) and \((4, 6)\). Which stored example is nearest to the new one? To answer, we need a ruler that works on pairs of numbers. And because a real data table has many columns, not two, the ruler must also work on lists of five, fifty or five hundred numbers, where there is no picture to measure on. How can a distance exist where nothing can be drawn?

From the last lesson

1. Which side of a right triangle is the hypotenuse?

Show answer

The side opposite the right angle. It is the longest side.

2. A right triangle has legs 6 and 8. How long is its hypotenuse?

Show answer

\[ \sqrt{36 + 64} = \sqrt{100} = 10 . \]

Intuition

From \({P = (1, 2)}\) to \({Q = (4, 6)}\) the changes are 3 across and 4 up (M01.2.1). Draw them: the across move and the up move meet at a right angle, so they are the legs of a right triangle, and the straight line from \(P\) to \(Q\) is its hypotenuse. Pythagoras’ theorem (M01.2.2) gives its length:

\[ \sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5 . \]

That is the distance from \(P\) to \(Q\).

A numbered grid with the blue point P = (1, 2) and the sky-blue point Q = (4, 6). Dashed green lines run 3 across from P and then 4 up to Q, with a small square at their right-angled corner, and are labelled 3 across and 4 up. A thick vermillion line joins P to Q directly and is labelled distance 5. Above them the working reads: d equals the square root of 3 squared plus 4 squared, which is the square root of 25, which is 5.
M01.2.3-F1

The two changes between two points are the legs of a right triangle. The straight line between the points is its hypotenuse, so Pythagoras gives the distance.

Nothing here depended on 3 and 4. For any two points the recipe is the same: subtract to get the changes, square each change, add the squares, and take the square root.

Build it up

Step 1. On a line. On the number line the distance between two numbers is the size of their difference, written with bars (M01.1.1). From 1 to 4 it is \({\abs{4 - 1}}\), which is 3, and from 4 back to 1 it is \({\abs{1 - 4}}\), which is 3 again.

Step 2. In the plane. The two legs of the triangle have the lengths \({\abs{4 - 1}}\) and \({\abs{6 - 2}}\). Pythagoras squares them, and squaring makes the bars unnecessary, because a number and its negative have the same square: \({(-3)^2}\) and \(3^2\) are both 9.

Step 3. The order does not matter. From \(Q\) back to \(P\) the changes are \({-3}\) and \({-4}\). Their squares are 9 and 16, as before, so the distance is 5 either way.

Step 4. The midpoint is halfway. From \(P\) to the midpoint \({M = (2.5, 4)}\) the changes are 1.5 and 2, so

\[ \begin{aligned} \sqrt{1.5^2 + 2^2} &= \sqrt{2.25 + 4} \\ &= \sqrt{6.25} = 2.5 . \end{aligned} \]

From \(M\) to \(Q\) the changes are again 1.5 and 2. The midpoint is 2.5 from each end, half of 5.

Step 5. A third axis. A point in space needs three numbers. Lay the plane of the x-axis and the y-axis flat, like a floor, so that the y-axis now runs along the floor. Add a third axis, the z-axis, standing upright at the origin, at right angles to the other two. Take \({A = (1, 2, 3)}\) and \({B = (2, 4, 5)}\). The changes are

\[ \begin{aligned} 2 - 1 &= 1 \text{ across}, \\ 4 - 2 &= 2 \text{ along}, \\ 5 - 3 &= 2 \text{ up}. \end{aligned} \]

Walk from \(A\) along the floor first, using the first two changes, and then straight up. Along the floor, the first two changes are the legs of a right triangle, so the floor distance is

\[ \sqrt{1^2 + 2^2} = \sqrt{5} . \]

The way up stands at right angles to every line on the floor, like a flagpole on flat ground, so the floor line and the way up are the legs of a second right triangle:

\[ \begin{aligned} d^2 &= (\sqrt{5})^2 + 2^2 \\ &= 5 + 4 = 9, \\ d &= 3 . \end{aligned} \]

A box drawn in three dimensions, with a small key showing the directions of the x, y and z axes. Its corner A = (1, 2, 3) is a blue dot and the opposite corner B = (2, 4, 5) is a sky-blue dot. A dashed green line crosses the bottom face of the box from A to the corner below B, labelled floor: the square root of 1 squared plus 2 squared, the square root of 5. A dashed green upright line rises from there to B, labelled up: 2. Right angles are marked at the corners. A thick vermillion line runs through the inside of the box from A to B, labelled the square root of 5 + 2 squared = 3.
M01.2.3-F2

Pythagoras twice: once along the floor, from the first two changes, and once more up the side, from the floor distance and the third change.

The distance in space is Pythagoras used twice. The three changes were squared and added, just as two were in the plane, and the square root was taken at the end.

The formal statement

NoteDefinition: distance

The distance between two points \({P = (p_1, p_2)}\) and \({Q = (q_1, q_2)}\) of the plane is

\[ d(P, Q) = \sqrt{(q_1 - p_1)^2 + (q_2 - p_2)^2} . \]

For two points with \(n\) coordinates each, \({P = (p_1, \dots, p_n)}\) and \({Q = (q_1, \dots, q_n)}\), the distance \(d\) is the positive square root of

\[ \begin{aligned} d^2 &= (q_1 - p_1)^2 + (q_2 - p_2)^2 \\ &\quad + \dots + (q_n - p_n)^2 . \end{aligned} \]

It is called the Euclidean distance.

Why it holds in the plane. Walk from \({P = (p_1, p_2)}\) across to the corner \((q_1, p_2)\), then up to \({Q = (q_1, q_2)}\). The first leg has length \({\abs{q_1 - p_1}}\) and the second has length \({\abs{q_2 - p_2}}\). They meet at a right angle, and the straight line from \(P\) to \(Q\) is the side opposite it. Pythagoras’ theorem gives

\[ \begin{aligned} d^2 &= \abs{q_1 - p_1}^2 + \abs{q_2 - p_2}^2 \\ &= (q_1 - p_1)^2 + (q_2 - p_2)^2 . \end{aligned} \]

The second line drops the bars, because a number and its negative have the same square. A distance is never negative, so \(d\) is the positive square root. If one change is zero there is no triangle, only a straight walk, and the formula still gives the right answer: the size of the other change.

Why it holds in space. As in Step 5, the floor distance \(f\) comes from the first two changes,

\[ f^2 = (q_1 - p_1)^2 + (q_2 - p_2)^2 , \]

and the way up is at right angles to the floor, so

\[ \begin{aligned} d^2 &= f^2 + (q_3 - p_3)^2 \\ &= (q_1 - p_1)^2 + (q_2 - p_2)^2 \\ &\quad + (q_3 - p_3)^2 . \end{aligned} \]

Beyond three coordinates. A fourth axis would have to stand at right angles to all three of the others, and our world has no room for it. There is no picture to measure on, so the formula is taken as the definition: each new coordinate adds one more squared change under the root, exactly as the third coordinate did. For \({n = 2}\) and \({n = 3}\) the definition agrees with the ruler. Lesson M01.7.2 writes the long sum with a sigma.

This is how machine learning measures how alike two examples are. A row of a data table with \(n\) numeric columns is a point with \(n\) coordinates, one per feature. It cannot be drawn, but its distance from any other row can be computed.

A trace in five rows of boxes. The first two rows are two rows of a data table with five features each: a = 5, 3, 4, 1, 2 in blue boxes and b = 4, 3, 5, 2, 2 in sky-blue boxes. The third row, in green, holds the changes b minus a: minus 1, 0, 1, 1, 0. The fourth row holds their squares: 1, 0, 1, 1, 0. Their sum, 3, sits in a highlighted box, and the last line gives the distance, the square root of 3, about 1.7321.
M01.2.3-F3

Five features, one distance. Subtract feature by feature, square, add, and take the square root.

Go deeper: three facts that every distance obeys

The formula has three properties that make it behave like a distance.

  1. It is never negative, and it is zero only when every change is zero, that is when the two points are the same point.
  2. It is the same in both directions, \({d(P, Q) = d(Q, P)}\), because swapping the points only flips the sign of each change.
  3. A detour is never shorter: going from \(P\) to \(R\) by way of a third point \(Q\) is at least as long as going straight. With \({P = (1, 2)}\), \({Q = (4, 6)}\) and \({R = (5, 4)}\), the detour is 5 plus \(\sqrt{5}\), about 7.2361, and the straight path is \({\sqrt{20} \approx 4.4721}\).

The third fact is the triangle inequality. Lessons M02.3.2 and M02.3.3 state and prove it for any number of coordinates.

Worked example

Which stored point is nearest to the new point \((3, 3)\)? Compute every distance. The changes from the new point to the four stored points are \({(-2, -1)}\), \({(-1, 0)}\), \((0, 2)\) and \((1, 3)\). Square them, add, and take the square root.

Stored point Squares added Distance
(1, 2) 4 + 1 = 5 ≈ 2.2361
(2, 3) 1 + 0 = 1 1
(3, 5) 0 + 4 = 4 2
(4, 6) 1 + 9 = 10 ≈ 3.1623

The last column holds \(\sqrt{5}\), 1, 2 and \(\sqrt{10}\). The smallest is 1, so the nearest stored point is \((2, 3)\), at distance 1.

A numbered grid with the four blue data points (1, 2), (2, 3), (3, 5) and (4, 6) and a sky-blue diamond for the new point (3, 3). Thin lines join the new point to each data point, labelled with the distances: about 2.2361 to (1, 2), 1 to (2, 3), 2 to (3, 5) and about 3.1623 to (4, 6). The line to (2, 3) is thick and vermillion, and (2, 3) has a yellow disc behind it, marked nearest.
M01.2.3-F4

Every distance from the new point. The point \((2, 3)\) is nearest, at distance 1.

Notice that the squared distances, 5, 1, 4 and 10, come in the same order as the distances. To rank points by distance you can skip the square roots, which is how lesson ML01.3.1 saves work. To measure a distance you cannot.

Code

From scratch first. The function walks through the coordinates, however many there are.

import math

def distance(p, q):
    """The straight-line distance between two points with the same number of coordinates."""
    total = 0
    for k in range(len(p)):            # one pass for each coordinate
        change = q[k] - p[k]           # the change in this coordinate
        total = total + change ** 2    # add its square
    return math.sqrt(total)            # the positive square root of the sum

print("P to Q:", distance((1, 2), (4, 6)))
print("P to M and M to Q:", distance((1, 2), (2.5, 4)), distance((2.5, 4), (4, 6)))
print("A to B in space:", distance((1, 2, 3), (2, 4, 5)))
P to Q: 5.0
P to M and M to Q: 2.5 2.5
A to B in space: 3.0

Now the worked example: one distance per stored point, keeping the best so far (the pattern of P01.3.4).

points = [(1, 2), (2, 3), (3, 5), (4, 6)]
query = (3, 3)

best_point = None
best_distance = None
for point in points:
    d = distance(query, point)
    print(point, round(d, 4))
    if best_distance is None or d < best_distance:   # a new best
        best_point = point
        best_distance = d
print("nearest:", best_point, "at distance", best_distance)
(1, 2) 2.2361
(2, 3) 1.0
(3, 5) 2.0
(4, 6) 3.1623
nearest: (2, 3) at distance 1.0

The same function measures two rows of a table with five features each. Nothing in it mentions two or three coordinates.

a = (5, 3, 4, 1, 2)     # one row: five features
b = (4, 3, 5, 2, 2)     # another row
print("a to b:", round(distance(a, b), 4))
a to b: 1.7321

The library versions: math.dist takes two points of any length, and NumPy, previewed here ahead of P02, measures the length of the difference of two arrays with numpy.linalg.norm.

import numpy as np

print(math.dist((1, 2), (4, 6)), math.dist((1, 2, 3), (2, 4, 5)))
P = np.array([1, 2])
Q = np.array([4, 6])
print(np.linalg.norm(Q - P))       # Q - P subtracts coordinate by coordinate
5.0 3.0
5.0

This is the distance of k-nearest neighbours (ML01.3): a new example takes its label from the stored examples nearest to it.

Explore

The module’s interactive, the point and arrow explorer, lives in lesson M01.2.4. Drag its two points: the distance is recomputed from the two changes as you move, and the midpoint stays at half of it.

Pitfalls

Two panels showing the same box in space with corners A = (1, 2, 3) and B = (2, 4, 5). The left panel is marked with a cross and titled Two coordinates: wrong. A thick purple line runs across the floor of the box from A to the corner below B, labelled the shadow, about 2.2361, and the height of the box is ignored. The right panel is marked with a tick and titled All three: right. A thick vermillion line runs from A through the box to B, labelled 3.
M01.2.3-F5

Wrong beside right. A function that loops over only two coordinates measures the shadow of the line on the floor, about 2.2361. All three coordinates give the true distance, 3.

“My distance function works in the plane, so it works in space.”

Only if it loops over every coordinate. Code written as for k in range(2) silently ignores the third coordinate and returns \({\sqrt{5} \approx 2.2361}\) for \({A = (1, 2, 3)}\) and \({B = (2, 4, 5)}\): the shadow on the floor, not the distance. Loop over range(len(p)), as the function above does. math.dist goes further and refuses, with an error, two points of different lengths.

“A negative change squared is negative.”

A negative number times a negative number is positive:

\[ (-2)^2 = (-2) \times (-2) = 4 . \]

Watch out in code: Python reads -2 ** 2 as \({-(2^2)}\), which is \({-4}\), because powers are worked out before the minus sign (the order of operations of M01.1.2). Write (-2) ** 2, or square a name that holds the change, as distance does.

“The squared distance will do.”

For ranking neighbours it will, because squaring keeps the order. For measuring it will not: the midpoint is half the distance from \(P\) to \(Q\), 2.5 out of 5, but only a quarter of the squared distance, 6.25 out of 25.

“Every coordinate counts the same, whatever its units.”

It counts by its size. Measure the second coordinate of every point in cents instead of euros and its changes become 100 times bigger, so they swamp the first coordinate’s changes in the sum. Lesson ML01.3.3 shows how a nearest-neighbour method fixes this by rescaling each feature.

Check yourself

Recall

1. What is the distance from \((2, 1)\) to \((5, 5)\)?

Show answer

The changes are 3 and 4, so the distance is \({\sqrt{9 + 16}}\), which is 5.

2. Why does it not matter which point you subtract from which?

Show answer

Each change is squared, and a number and its negative have the same square.

3. How far is the midpoint \((2.5, 4)\) from \({P = (1, 2)}\)?

Show answer

2.5, which is half of the distance 5 from \(P\) to \(Q\).

4. What is the distance from \((0, 0, 0)\) to \((1, 2, 2)\)?

Show answer

\[ \sqrt{1 + 4 + 4} = \sqrt{9} = 3 . \]

5. A data table has 10 numeric columns. What is each row, and how far apart are two rows?

Show answer

Each row is a point with 10 coordinates. Their distance is the square root of the sum of the 10 squared differences, one per column.

Exercises

1. ★ Find the distance from \({(-1, 3)}\) to \({(5, -5)}\).

Show solution

The changes are

\[ \begin{aligned} 5 - (-1) &= 6, \\ -5 - 3 &= -8 . \end{aligned} \]

So \({d = \sqrt{36 + 64}}\), which is \({\sqrt{100} = 10}\).

2. ★★ A new example arrives at \((1, 4)\). Which of the course’s four data points is nearest to it, and how far away is it?

Show solution

The changes from \((1, 4)\) to the four points are \({(0, -2)}\), \({(1, -1)}\), \((2, 1)\) and \((3, 2)\), so:

Stored point Squares added Distance
(1, 2) 0 + 4 = 4 2
(2, 3) 1 + 1 = 2 ≈ 1.4142
(3, 5) 4 + 1 = 5 ≈ 2.2361
(4, 6) 9 + 4 = 13 ≈ 3.6056

The nearest is \((2, 3)\), at distance \({\sqrt{2} \approx 1.4142}\).

3. ★★★ Prove that the midpoint \(M\) of any two points \(P\) and \(Q\) of the plane is half as far from \(P\) as \(Q\) is.

Show solution

Lesson M01.2.1 reached \(M\) from \(P\) by half of each change, so the changes from \(P\) to \(M\) are \({\tfrac{1}{2}(q_1 - p_1)}\) and \({\tfrac{1}{2}(q_2 - p_2)}\). Square and add them:

\[ \begin{aligned} d(P, M)^2 &= \tfrac{1}{4}(q_1 - p_1)^2 \\ &\quad + \tfrac{1}{4}(q_2 - p_2)^2 \\ &= \tfrac{1}{4}\, d(P, Q)^2 . \end{aligned} \]

The first line uses \({(\tfrac{1}{2}x)^2 = \tfrac{1}{4}x^2}\), and the second takes out the common factor \(\tfrac{1}{4}\). Neither distance is negative, and the positive square root of \(\tfrac{1}{4}\) is \(\tfrac{1}{2}\), so \({d(P, M) = \tfrac{1}{2}\, d(P, Q)}\). The same steps from \(M\) to \(Q\) give the other half. With the course’s points, 2.5 is half of 5.

Summary card

Distance is Pythagoras applied to the changes: square them, add, take the root.

The anchor figure again: the points P = (1, 2) and Q = (4, 6) with the dashed changes 3 across and 4 up, and the vermillion straight line between them, labelled distance 5.
M01.2.3-F1

Changes are the legs; distance is the hypotenuse.

\[ \begin{aligned} d^2 &= (q_1 - p_1)^2 \\ &\quad + (q_2 - p_2)^2 \end{aligned} \]

  • In the plane: the two changes are the legs, the distance is the hypotenuse.
  • In space: one more squared change, \({(q_3 - p_3)^2}\), under the root.
  • In \(n\) coordinates: one squared change per coordinate, the Euclidean distance.
  • In Python: math.dist(p, q), or numpy.linalg.norm(q - p) for arrays.

Sources and next steps

Sources. Each was opened and checked against this lesson on 12 November 2026.

  • OpenStax, Algebra and Trigonometry 2e, Section 2.1, under “Using the Distance Formula”: the distance formula for \((x_1, y_1)\) and \((x_2, y_2)\), “derived from the Pythagorean Theorem”.
  • OpenStax, Calculus Volume 3, Section 2.2, Theorem 2.2, “The Distance between Two Points in Space”: the three-coordinate formula, with the hint to find first the distance along the base of the box (Figure 2.28).
  • Marc Peter Deisenroth, A. Aldo Faisal and Cheng Soon Ong, Mathematics for Machine Learning, Example 3.2 (the Euclidean norm, equation 3.4, “computes the Euclidean distance of \(\vect{x}\) from the origin”) and Definition 3.6 (distance, equation 3.21, called the Euclidean distance with the dot product).
  • Python 3.12 documentation, math.dist: the Euclidean distance between two points “each given as a sequence (or iterable) of coordinates”, which “must have the same dimension”.
  • NumPy, numpy.linalg.norm: with no ord and no axis, the 2-norm of a vector.

Next. M01.2.4 Arrows: a first look at vectors keeps the two changes together as one object, an arrow. The nearest-neighbour methods of ML01.3 put this distance to work.

This lesson unlocks

M01.2.4 Arrows: a first look at vectors ML01.3.1 Classify by your nearest neighbour

Your progress is saved in this browser only. No account, no tracking.
Back to top