Length of a Vector
The length (or norm) of a vector measures how long its arrow is. In and it comes straight from the Pythagorean theorem, and the same formula works in any number of dimensions. With length come distances between points and unit vectors, which are pure directions.
The formula
For :
In this is the hypotenuse of a right triangle with legs and (Pythagorean theorem). In , apply Pythagoras twice: first across the floor, , then up to the tip, .
import numpy as np
from sympy import Matrix, sqrt
v = np.array([2.0, -3.0, 6.0])
print("NumPy:", np.linalg.norm(v), "=", np.sqrt(np.sum(v ** 2)))
w = Matrix([1, 1, 2])
print("SymPy exact:", w.norm(), "≈", w.norm().evalf(6))
print("in 768 dimensions:", np.linalg.norm(np.ones(768)), "= sqrt(768) =", round(float(np.sqrt(768)), 4))NumPy: 7.0 = 7.0
SymPy exact: sqrt(6) ≈ 2.44949
in 768 dimensions: 27.712812921102035 = sqrt(768) = 27.7128
Properties
For all vectors and scalars :
| Property | Formula |
|---|---|
| non-negative | , and only for |
| scaling | |
| triangle inequality |
The scaling rule follows from the formula: . The triangle inequality says that a detour is never shorter than the direct path; its proof uses the dot product (Cauchy–Schwarz inequality).
Distance between points
The distance between points and is the length of the vector between them:
This is the Euclidean distance. For and : , so .
Unit vectors and normalizing
A unit vector has length 1. Dividing any non-zero vector by its length gives the unit vector in the same direction; this is called normalizing:
import numpy as np
def normalize(v, eps=1e-12):
n = np.linalg.norm(v)
if n < eps:
raise ValueError("cannot normalize the zero vector")
return v / n
aim = np.array([3.0, 0.0, 4.0])
d = normalize(aim)
print("direction:", d, " length:", np.linalg.norm(d))
speed = 12.0
print("velocity at speed 12:", speed * d)
try:
normalize(np.zeros(3))
except ValueError as e:
print("error:", e)direction: [0.6 0. 0.8] length: 1.0
velocity at speed 12: [7.2 0. 9.6]
error: cannot normalize the zero vector
"Direction times speed" is the standard way to build a velocity in games. The zero check matters: normalizing divides by zero and fills a game object with NaNs.
Other norms
The Euclidean norm is not the only way to measure size. Machine learning uses several:
| Norm | Formula | Used for |
|---|---|---|
| (Euclidean) | distances, ridge regularization, gradient clipping | |
| ("taxicab") | lasso regularization (makes weights sparse), city-block distance | |
| (max) | worst-case error, adversarial-robustness budgets |
import numpy as np
v = np.array([3.0, -4.0, 1.0])
print("L2:", round(float(np.linalg.norm(v)), 4))
print("L1:", float(np.linalg.norm(v, 1)))
print("Linf:", float(np.linalg.norm(v, np.inf)))L2: 5.099
L1: 8.0
Linf: 4.0
In software
- Games: "is the enemy within 10 m?" Compare squared lengths (
dx*dx + dy*dy < 100) to skip the square root, which is faster and just as correct since both sides are non-negative. - ML: k-nearest neighbours and k-means rely on distances; embeddings are often normalized to length 1 so that the dot product equals the cosine similarity (coming in The Dot Product).
- Deep learning: gradient clipping rescales a gradient to length at most by ; layer normalization rescales activation vectors.
See also Game Math: Length and Normalize.
Exercises
Exercise 1: Lengths
Find and .
Answer
7 and .
Solution
Exercise 2: Distance
Find the distance between and .
Answer
Solution
Exercise 3: Unit vector and scaling
Find the unit vector in the direction of , and a vector of length 15 pointing the opposite way.
Answer
and .
Solution
Exercise 4: Gradient clipping (code)
Write clip(g, c) that returns unchanged if , and otherwise rescaled to length . Test with and , and with and .
Answer
and .
Solution
, so multiply by .
import numpy as np
def clip(g, c):
n = np.linalg.norm(g)
return g if n <= c else g * (c / n)
print(clip(np.array([6.0, 8.0]), 5.0), clip(np.array([1.0, 1.0]), 5.0))[3. 4.] [1. 1.]
Test yourself
What is ?
- 7
- 17
- 13
- 169
If , what is ?
- -12
- 12
- 1
- 7
Why do games often compare squared distances instead of distances?
- It avoids a square root and gives the same comparison result
- Squared distances are more accurate
- Distances can be negative
- Square roots are not available on GPUs