TExcelTAD
Home › Math for Machine Learning › Distances, Angles and Orthogonality

Distances, Angles and Orthogonality

Once you have an inner product you get three more things for free: the distance between two vectors, the angle between them, and the notion of being perpendicular. Nearest-neighbour search, cosine similarity of embeddings and orthonormal bases all rest on these three ideas.

Distance and angle

The distance between x\mathbf{x} and y\mathbf{y} is the norm of their difference, and the angle ω\omega between nonzero vectors comes from Cauchy-Schwarz:

d(x,y)=∥x−y∥,cos⁡ω=⟨x,y⟩∥x∥ ∥y∥d(\mathbf{x}, \mathbf{y}) = \lVert \mathbf{x} - \mathbf{y} \rVert, \qquad \cos\omega = \frac{\langle \mathbf{x}, \mathbf{y} \rangle}{\lVert \mathbf{x} \rVert\,\lVert \mathbf{y} \rVert}

cos⁡ω\cos\omega is the cosine similarity. It ignores length and only measures direction: 11 for the same direction, 00 for perpendicular, −1-1 for opposite. For unit vectors, distance and cosine are tied together:

∥x−y∥2=∥x∥2+∥y∥2−2⟨x,y⟩=2−2cos⁡ω\lVert \mathbf{x} - \mathbf{y} \rVert^2 = \lVert \mathbf{x} \rVert^2 + \lVert \mathbf{y} \rVert^2 - 2\langle \mathbf{x}, \mathbf{y} \rangle = 2 - 2\cos\omega

so ranking unit vectors by Euclidean distance or by cosine similarity gives the same order. That is why vector databases normalize embeddings.

python · try it yourself
import numpy as np

docs = {"cats": np.array([3.0, 1.0, 0.0]), "kittens": np.array([6.0, 2.5, 0.2]),
        "stocks": np.array([0.1, 0.2, 4.0])}
q = np.array([1.0, 0.3, 0.0])
def cos(a, b): return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
for name, v in docs.items():
    print(f"{name:8s} cosine {cos(q, v):.4f}  euclid {np.linalg.norm(q - v):.4f}")
u = {k: v / np.linalg.norm(v) for k, v in docs.items()}
qn = q / np.linalg.norm(q)
print("unit vectors, 2 - 2cos = squared distance:",
      all(np.isclose(np.linalg.norm(qn - v)**2, 2 - 2 * (qn @ v)) for v in u.values()))
cats     cosine 0.9995  euclid 2.1190
kittens  cosine 0.9942  euclid 5.4663
stocks   cosine 0.0383  euclid 4.1012
unit vectors, 2 - 2cos = squared distance: True

Raw Euclidean distance says "kittens" is farther from the query than "stocks" only because its vector is longer; the cosine looks past the length.

Orthogonality and orthonormal bases

x\mathbf{x} and y\mathbf{y} are orthogonal, x⊥y\mathbf{x} \perp \mathbf{y}, if ⟨x,y⟩=0\langle \mathbf{x}, \mathbf{y} \rangle = 0. A basis b1,…,bn\mathbf{b}_1, \ldots, \mathbf{b}_n is orthonormal if ⟨bi,bj⟩=0\langle \mathbf{b}_i, \mathbf{b}_j \rangle = 0 for i≠ji \ne j and each has length 1. Coordinates in an orthonormal basis are just inner products, no system to solve:

x=∑i=1n⟨x,bi⟩ bi\mathbf{x} = \sum_{i=1}^{n} \langle \mathbf{x}, \mathbf{b}_i \rangle\,\mathbf{b}_i

A square matrix QQ with orthonormal columns is orthogonal: QTQ=IQ^T Q = I, so Q−1=QTQ^{-1} = Q^T, and it preserves lengths and angles. The Gram-Schmidt process (or np.linalg.qr) turns any basis into an orthonormal one.

python · try it yourself
import numpy as np

B = np.array([[1.0, 1.0, 0.0],
              [1.0, 0.0, 1.0],
              [0.0, 1.0, 1.0]]).T           # an ordinary basis as columns
Q, _ = np.linalg.qr(B)                     # orthonormalize
print("Q^T Q = I:", np.allclose(Q.T @ Q, np.eye(3)))
x = np.array([2.0, -1.0, 3.0])
coords = Q.T @ x                           # inner products with the basis vectors
print("coordinates:", np.round(coords, 4) + 0)
print("rebuilt x:", np.round(Q @ coords, 10))
print("length kept:", np.isclose(np.linalg.norm(Q @ x), np.linalg.norm(x)))
Q^T Q = I: True
coordinates: [-0.7071  3.6742  0.    ]
rebuilt x: [ 2. -1.  3.]
length kept: True

Orthogonal complement

The orthogonal complement U⊥U^\perp of a subspace U⊆RDU \subseteq \mathbb{R}^D is the set of all vectors orthogonal to every vector of UU, and dim⁡U+dim⁡U⊥=D\dim U + \dim U^\perp = D. A plane through the origin in R3\mathbb{R}^3 has a line as its complement, spanned by the normal vector. The null space of AA is the orthogonal complement of its row space.

In software

  • Semantic search ranks documents by cosine similarity of embeddings (Embeddings and Cosine Similarity); FAISS and pgvector offer inner-product and ℓ2\ell_2 indexes.
  • Orthogonal weight initialization (torch.nn.init.orthogonal_) keeps signal norms stable through deep linear stacks.
  • QR factorization solves least squares more stably than the normal equations.

Exercises

Exercise 1: Angle by hand

Find the angle between (1,0,1)(1, 0, 1) and (0,1,1)(0, 1, 1).

Answer

60∘60^\circ.

Solution

cos⁡ω=0+0+122=12\cos\omega = \frac{0 + 0 + 1}{\sqrt{2}\sqrt{2}} = \frac{1}{2}, so ω=arccos⁡12=π3\omega = \arccos\frac{1}{2} = \frac{\pi}{3}.

Exercise 2: Orthonormal coordinates

With the orthonormal basis b1=12(1,1)\mathbf{b}_1 = \frac{1}{\sqrt{2}}(1, 1), b2=12(1,−1)\mathbf{b}_2 = \frac{1}{\sqrt{2}}(1, -1), find the coordinates of (3,1)(3, 1).

Answer

(22,2)(2\sqrt{2}, \sqrt{2}).

Solution
⟨x,b1⟩=3+12=22⟨x,b2⟩=3−12=2\begin{aligned} \langle \mathbf{x}, \mathbf{b}_1 \rangle &= \tfrac{3 + 1}{\sqrt{2}} = 2\sqrt{2} \\ \langle \mathbf{x}, \mathbf{b}_2 \rangle &= \tfrac{3 - 1}{\sqrt{2}} = \sqrt{2} \end{aligned}

Check: 22 b1+2 b2=(2,2)+(1,−1)=(3,1)2\sqrt{2}\,\mathbf{b}_1 + \sqrt{2}\,\mathbf{b}_2 = (2, 2) + (1, -1) = (3, 1).

Exercise 3: Nearest neighbour (code)

Which of (1,2)(1, 2), (4,4)(4, 4), (−1,3)(-1, 3) has the largest cosine similarity with (2,3)(2, 3)?

Answer

(1,2)(1, 2).

Solution
python · try it yourself
import numpy as np
q = np.array([2.0, 3.0])
for v in ([1.0, 2.0], [4.0, 4.0], [-1.0, 3.0]):
    v = np.array(v)
    print(v, round(float(q @ v / np.linalg.norm(q) / np.linalg.norm(v)), 4))
[1. 2.] 0.9923
[4. 4.] 0.9806
[-1.  3.] 0.6139

Test yourself

The cosine similarity of x\mathbf{x} and 2x2\mathbf{x} is…

  1. 0
  2. 0.5
  3. 1
  4. 2

If QQ is orthogonal, then Q−1Q^{-1} equals…

  1. QQ
  2. QTQ^T
  3. −Q-Q
  4. II

For unit vectors, ∥x−y∥2\lVert \mathbf{x} - \mathbf{y} \rVert^2 equals…

  1. 2−2cos⁡ω2 - 2\cos\omega
  2. 1+cos⁡ω1 + \cos\omega
  3. cos⁡2ω\cos^2\omega
  4. 00