The Pythagorean Theorem
In a right triangle, the squares of the two shorter sides add up to the square of the longest side: . This one equation gives you the distance between any two points on a map, a screen or in a 3D world, which makes it one of the most-used formulas in all of programming.
The statement
A right triangle has one 90° angle. The two sides that form that angle are the legs ( and ); the side opposite it, always the longest, is the hypotenuse ().
|\
| \
b | \ c
| \
|____\
aClassic example: legs 3 and 4 give , so the hypotenuse is .
Why it is true
Take four copies of the triangle and arrange them inside a big square of side , with their hypotenuses forming a tilted square in the middle. The area of the big square can be counted two ways:
There are hundreds of other proofs; this one needs only areas and the expansion .
Finding a missing side
import math
# Hypotenuse from two legs
print("legs 5, 12 -> c =", math.sqrt(5**2 + 12**2))
print("math.hypot ->", math.hypot(5, 12))
# A missing leg from the hypotenuse and the other leg
c, a = 10, 6
print("c 10, a 6 -> b =", math.sqrt(c**2 - a**2))
# A ladder 5 m long, foot 1.5 m from the wall: how high does it reach?
print(f"ladder reach = {math.sqrt(5**2 - 1.5**2):.2f} m")legs 5, 12 -> c = 13.0
math.hypot -> 13.0
c 10, a 6 -> b = 8.0
ladder reach = 4.77 m
Whole-number solutions such as (3, 4, 5), (5, 12, 13), (8, 15, 17) and (6, 8, 10) are called Pythagorean triples. Multiplying a triple by any whole number gives another one.
Note: The converse also holds: if , the triangle has a right angle. Builders use a 3-4-5 rope or tape measure to lay out square corners.
Distance between two points
On a grid, the horizontal gap and the vertical gap are the legs of a right triangle, and the straight-line distance is its hypotenuse:
In 3D, apply the theorem twice and you get one more term: . See The Coordinate Plane for points and grids.
In software: game distances
A game constantly asks "is this enemy within range?". The direct way computes a square root for every pair. But if both distances are non-negative, exactly when , so games compare squared distances and skip the root:
import math
player = (2.0, 3.0)
enemies = {"slime": (5.0, 7.0), "bat": (9.0, 3.5), "ghost": (2.5, 1.0)}
attack_range = 5.0
for name, (x, y) in enemies.items():
dx, dy = x - player[0], y - player[1]
d2 = dx * dx + dy * dy # squared distance, no sqrt
in_range = d2 <= attack_range ** 2
print(f"{name:6} d² = {d2:6.2f} d = {math.sqrt(d2):5.2f} in range: {in_range}")
closest = min(enemies, key=lambda n: math.dist(player, enemies[n]))
print("closest:", closest)slime d² = 25.00 d = 5.00 in range: True
bat d² = 49.25 d = 7.02 in range: False
ghost d² = 4.25 d = 2.06 in range: True
closest: ghost
Sorting or picking the minimum works on squared distances too, because squaring keeps the order of non-negative numbers. The square root is only needed when you want the actual distance, for example to display it or to move exactly 5 units. More in length and distance and circles and spheres.
Other places it shows up:
- Screens: a "27-inch" monitor is measured along its diagonal; a 16:9 screen of width 16 and height 9 has a diagonal of in the same units.
- Machine learning: the Euclidean distance between feature vectors drives k-nearest neighbours and k-means clustering.
- Touch and mouse input: a tap becomes a drag only once the pointer has moved more than a few pixels, a squared-distance check.
Exercises
Exercise 1: Hypotenuse
Find the hypotenuse for legs 8 and 15, and for legs 1 and 1.
Answer
17 and .
Solution
Exercise 2: Missing leg
A right triangle has hypotenuse 25 and one leg 7. Find the other leg.
Answer
Solution
Exercise 3: Is it a right triangle?
Which side lengths form a right triangle: (9, 12, 15), (4, 5, 6), (20, 21, 29)?
Answer
(9, 12, 15) and (20, 21, 29) do; (4, 5, 6) does not.
Solution
Check with the longest side.
for a, b, c in [(9, 12, 15), (4, 5, 6), (20, 21, 29)]:
print((a, b, c), a*a + b*b, c*c, a*a + b*b == c*c)(9, 12, 15) 225 225 True
(4, 5, 6) 41 36 False
(20, 21, 29) 841 841 True
Exercise 4: 3D distance
A drone flies from to metres. How far is that in a straight line?
Answer
7 m.
Solution
import math
print(math.dist((1, 2, 0), (7, 5, 2)))7.0
Exercise 5: Pickup radius
Write in_radius(p, q, r) that returns True when point is within distance of , without calling sqrt. Test with , and , , .
Answer
True, False, True.
Solution
Compare the squared distance with .
def in_radius(p, q, r):
dx, dy = q[0] - p[0], q[1] - p[1]
return dx * dx + dy * dy <= r * r
print([in_radius((0, 0), q, 10) for q in [(6, 8), (7, 8), (-10, 0)]])[True, False, True]
is exactly 10 away (); gives .
Test yourself
The legs of a right triangle are 9 and 12. How long is the hypotenuse?
- 21
- 15
- 108
Why do games often compare squared distances?
- Squared distances are more accurate
- It avoids a square root and gives the same comparison result
- The Pythagorean theorem only works with squares
- Engines cannot compute square roots
What is the distance between and ?
- 7
- 25
- 5