Lengths and Distances
An inner product hands you two things immediately and for free. Length is the inner product of a vector with itself, square-rooted. Distance is the length of a difference. Both definitions are one line long, and between them they underpin every nearest-neighbour query, every clustering algorithm and every loss function you will meet.
The free part deserves emphasis. You do not choose a norm and a distance separately from an inner product — once the inner product is fixed, both are determined. Which means a change of inner product silently changes what “close” means, and this page ends by measuring exactly how much.
What you’ll learn
Section titled “What you’ll learn”- The induced norm, and the fact that every inner product gives a norm while not every norm comes from an inner product.
- The Cauchy-Schwarz inequality, why it is the thing that makes the cosine of an angle well defined, and when it holds with equality.
- The definition of a metric and its three axioms, and how they line up with the norm axioms.
- The book’s Remark that an inner product and a metric behave in opposite directions — and why that is not a curiosity.
- The measured demonstration that , , and Mahalanobis distance disagree about which of nine candidates is nearest.
Intuition: the ruler is built into the tape measure
Section titled “Intuition: the ruler is built into the tape measure”Suppose someone hands you a device that, given two directions, reports how much they overlap. You can build a ruler out of it without asking for anything else: to measure a stick, ask the device how much the stick overlaps with itself. A long stick overlaps itself a lot.
That is exactly what the induced norm does, and the square root is there for the reason you would expect — overlap-with-self scales with the square of length (an inner product is bilinear, so doubling the vector quadruples the answer), so you take a square root to get back to something that scales linearly.
Distance is then a second free step: the distance between two points is the length of the arrow from one to the other.
flowchart TD IP["⟨x, y⟩
an inner product"] IP --> NORM["‖x‖ = √⟨x,x⟩
the INDUCED norm, Eq 3.16"] NORM --> DIST["d(x,y) = ‖x − y‖ = √⟨x−y, x−y⟩
a METRIC, Def 3.6"] IP --> CS["Cauchy-Schwarz
|⟨x,y⟩| ≤ ‖x‖ ‖y‖
Eq 3.17"] CS --> COS["so ⟨x,y⟩/(‖x‖‖y‖) lies in [−1, 1]
and can be a cosine — §3.4"] NORM --> ONEWAY["every inner product gives a norm
NOT every norm comes from one
(l1 and l-infinity do not)"] DIST --> AXIOMS["positive definite · symmetric · triangle inequality"]
The bottom-left node is the asymmetry to remember. Inner products are a strictly smaller world than norms. The and norms of the previous page are genuine norms that no inner product produces — which is why has no notion of angle attached to it and does.
The math
Section titled “The math”The induced norm
Section titled “The induced norm”Check the three norm axioms against it and each one comes from an inner product property:
| norm axiom | comes from |
|---|---|
| bilinearity: , then the square root | |
| , zero only at | positive definiteness, directly |
| Cauchy-Schwarz — see below |
The third one is not automatic, and Cauchy-Schwarz is exactly the tool that supplies it.
Cauchy-Schwarz
Section titled “Cauchy-Schwarz”Two consequences, and both matter.
It makes the cosine possible. Dividing through gives
and a number guaranteed to lie in is a number you are allowed to call . Without Cauchy-Schwarz, of that ratio might not exist and §3.4 would have nothing to define.
It gives the triangle inequality. Expand and bound:
The single inequality step replaces by , which is Cauchy-Schwarz, and taking square roots finishes it.
Distance and metrics
Section titled “Distance and metrics”Note that a metric needs only these three. It does not need to come from a norm, let alone from an inner product — edit distance on strings and shortest-path distance on a graph are metrics with no vectors in sight. The hierarchy runs one way:
The remark worth pausing on
Section titled “The remark worth pausing on”The book adds a Remark that the inner product and the metric behave in opposite directions. Two vectors that are similar have a large inner product and a small distance; two that are dissimilar have a small inner product and a large distance.
This is not a curiosity, it is a recurring source of sign errors. A similarity has to be negated or inverted to be used as a distance, and code that treats an inner product as a distance will confidently return the farthest point when asked for the nearest. Note also that the correspondence is not a simple negation — expanding
shows that the distance depends on the inner product and on both lengths. Ranking by inner product and ranking by distance agree only when all the vectors have the same length, which is exactly the normalisation that turns a dot product into a cosine.
Worked example by hand
Section titled “Worked example by hand”Example 3.5 from the book
Section titled “Example 3.5 from the book”Take . Under the dot product:
Now take instead the inner product of the book’s Equation 3.19,
and the same vector measures
Exactly , not approximately. The book’s phrasing is that this inner product makes us “perceive” as shorter than the dot product does. The reason is the negative off-diagonal entry: it subtracts a penalty proportional to , so vectors whose coordinates agree in sign are discounted. Under this inner product, is a unit vector.
The book’s Exercise 3.3, worked
Section titled “The book’s Exercise 3.3, worked”Compute the distance between and under two inner products. First the difference:
(a) Dot product. , so .
(b) With . First , row by row:
| row | working | result |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 |
Then , so .
The second answer is larger, and is a valid inner product: its eigenvalues are exactly , and . So the same two points are apart under one geometry and apart under another, and neither number is wrong.
import numpy as np
# Example 3.5
x = np.array([1.0, 1.0])
E = np.array([[1.0, -0.5], [-0.5, 1.0]])
print("Example 3.5: dot", np.sqrt(x @ x), " Eq 3.19", np.sqrt(x @ E @ x))
# Exercise 3.3
p = np.array([1.0, 2.0, 3.0])
q = np.array([-1.0, -1.0, 0.0])
d = p - q
A = np.array([[2.0, 1.0, 0.0], [1.0, 3.0, -1.0], [0.0, -1.0, 2.0]])
print("difference:", d)
print("A @ d :", A @ d)
print("(a) dot :", float(d @ d), "->", np.sqrt(float(d @ d)))
print("(b) A form:", float(d @ A @ d), "->", np.sqrt(float(d @ A @ d)))
print("A eigenvalues:", np.round(np.linalg.eigvalsh(A), 6),
" spd:", bool(np.all(np.linalg.eigvalsh(A) > 0)))Example 3.5: dot 1.4142135623730951 Eq 3.19 1.0
difference: [2. 3. 3.]
A @ d : [7. 8. 3.]
(a) dot : 22.0 -> 4.69041575982343
(b) A form: 47.0 -> 6.855654600401044
A eigenvalues: [1. 2. 4.] spd: TrueSee it move
Section titled “See it move”The first sketch tests the triangle inequality by hand. Drag the waypoint and watch the detour bar; it never falls below the direct bar, and it touches it exactly when the waypoint lies on the straight segment.
The second sketch is Example 3.5, made draggable. Two inner products, two unit sets, one vector, two lengths.
The third makes Cauchy-Schwarz into a bar you can try to break. You cannot.
From scratch
Section titled “From scratch”import numpy as np
def induced_norm(x, A=None):
"""sqrt(<x,x>). A=None means the dot product."""
q = x @ x if A is None else x @ A @ x
return np.sqrt(q)
def induced_distance(x, y, A=None):
return induced_norm(x - y, A)
# The metric axioms, tested on 4000 random triples.
rng = np.random.default_rng(9)
P = rng.normal(size=(4000, 3)) * 2
i = rng.integers(0, 4000, 4000)
j = rng.integers(0, 4000, 4000)
k = rng.integers(0, 4000, 4000)
dij = np.linalg.norm(P[i] - P[j], axis=1)
dji = np.linalg.norm(P[j] - P[i], axis=1)
djk = np.linalg.norm(P[j] - P[k], axis=1)
dik = np.linalg.norm(P[i] - P[k], axis=1)
print("symmetry violations: ", int(np.sum(np.abs(dij - dji) > 0)))
print("negative distances: ", int(np.sum(dij < 0)))
print("triangle violations: ", int(np.sum(dik > dij + djk + 1e-12)), "of 4000")
# And Cauchy-Schwarz, including the equality case.
X = rng.normal(size=(10000, 5))
Y = rng.normal(size=(10000, 5))
Y[:220] = X[:220] * rng.uniform(0.3, 2.5, size=(220, 1)) # planted parallel pairs
lhs = np.abs(np.sum(X * Y, axis=1))
rhs = np.linalg.norm(X, axis=1) * np.linalg.norm(Y, axis=1)
ratio = lhs / rhs
print("largest ratio seen: ", f"{ratio.max():.15f}")
print("pairs above 1: ", int(np.sum(ratio > 1 + 1e-12)))
print("smallest ratio among the parallel pairs:", f"{ratio[:220].min():.15f}")
print("median ratio in 5 dimensions:", f"{np.median(ratio[220:]):.6f}")symmetry violations: 0
negative distances: 0
triangle violations: 0 of 4000
largest ratio seen: 1.000000000000000
pairs above 1: 0
smallest ratio among the parallel pairs: 1.000000000000000
median ratio in 5 dimensions: 0.341057The last line is the interesting one. Cauchy-Schwarz permits the ratio to reach , and the planted parallel pairs do reach it exactly — but a random pair in five dimensions has a median ratio of only . Random high-dimensional vectors are nearly orthogonal, which is a fact this chapter will keep running into and which the next page names.
On real data
Section titled “On real data”Reading the plot
Section titled “Reading the plot”From the Cauchy-Schwarz scatter. Two things. First, the bound is tight: the amber points are not merely close to the line, they are on it, with a measured ratio of . The “if and only if” in the statement is real, and the equality case is not a measure-zero curiosity you can ignore — it is exactly the parallel pairs, which in practice means duplicated features and collinear columns.
Second, the empty region. Almost all the mass of the scatter sits well below the diagonal, and in five dimensions the median ratio over all ten thousand pairs is , and once the planted parallel pairs are excluded. Push the dimension up and that number falls further. Two random directions in high dimensions are nearly orthogonal, which is why cosine similarity between unrelated embeddings is small rather than random-looking.
From the four metric panels. The measured winners are:
| metric | nearest candidate | its distance |
|---|---|---|
| #1 at | ||
| #9 at | ||
| #3 at | ||
| Mahalanobis | #3 at |
Three distinct answers from four metrics, on nine candidates. But the more striking measurement is not the winner, it is the reshuffling of the whole ranking. Under the order is #9, #4, #3, #6, #5, #2, #1, #8, #7. Under Mahalanobis it is #3, #8, #7, #6, #2, #1, #9, #4, #5. Look at two entries in particular:
- Candidate #4 at is the second nearest under (distance ) and the last under Mahalanobis (distance ). It runs against the correlation of the surrounding cloud, so it is an unusual point even though it is not a distant one.
- Candidate #8 at is eighth of nine under and second under Mahalanobis. It is further away in plain kilometres and much more typical of the data.
If your pipeline does nearest-neighbour retrieval, the choice of metric is not a tuning detail — it is the model. The and Mahalanobis panels happen to agree on the winner here, and they agree by coincidence: likes #3 because neither of its coordinates is large, and Mahalanobis likes it because it lies along the cloud’s principal direction.
Pitfalls
Section titled “Pitfalls”Compare
Section titled “Compare”| notion | needs | gives | example that is only this |
|---|---|---|---|
| metric | three axioms on pairs | distances | edit distance on strings; shortest path on a graph |
| norm | metric + homogeneity + a vector space | lengths, so distances by subtraction | , |
| inner product | norm + the parallelogram law | lengths, distances and angles | the dot product; any SPD matrix |
Reading down the table, each row buys you more structure at the cost of more assumptions. Reading up, each row is a place you can retreat to when the assumptions fail — which is what happens when you move from Euclidean data to strings, graphs or distributions.
-
Why is the Cauchy-Schwarz inequality needed before an angle can be defined?
The same inequality also supplies the triangle inequality for the induced norm: expanding the squared norm of a sum and replacing the cross term by the product of the norms gives the result in one step.
pch.quizShowAnswer
B — It bounds the ratio of the inner product to the product of the norms inside [-1, 1], which is exactly the range in which arccos is defined — The same inequality also supplies the triangle inequality for the induced norm: expanding the squared norm of a sum and replacing the cross term by the product of the norms gives the result in one step.
-
Under the dot product, x = (1,1) has length sqrt(2). Under the book's Equation 3.19 the same vector has length exactly 1. What is going on?
The matrix [[1, -0.5], [-0.5, 1]] has eigenvalues 0.5 and 1.5, so it is a perfectly valid inner product. The computation is 1 - 0.5(1+1) + 1 = 1 exactly. The book's phrasing is that this inner product 'perceives' the vector as shorter.
pch.quizShowAnswer
B — The negative off-diagonal entry subtracts a penalty proportional to x1*x2, so vectors whose coordinates agree in sign are discounted — under that inner product (1,1) is a unit vector — The matrix [[1, -0.5], [-0.5, 1]] has eigenvalues 0.5 and 1.5, so it is a perfectly valid inner product. The computation is 1 - 0.5(1+1) + 1 = 1 exactly. The book's phrasing is that this inner product 'perceives' the vector as shorter.
-
Candidate #4 in the metric figure is the second nearest of nine under the Euclidean metric and the last under Mahalanobis. Why?
Mahalanobis distance is a genuine metric, induced by the inner product with matrix Sigma-inverse. Its ranking of the nine candidates is close to a reversal of the Euclidean one at the tail: candidate #8 goes the other way, from eighth under l2 to second under Mahalanobis.
pch.quizShowAnswer
B — It sits against the correlation direction of the surrounding cloud, so although it is not far in plain distance it is an atypical point — and Mahalanobis measures atypicality rather than displacement — Mahalanobis distance is a genuine metric, induced by the inner product with matrix Sigma-inverse. Its ranking of the nine candidates is close to a reversal of the Euclidean one at the tail: candidate #8 goes the other way, from eighth under l2 to second under Mahalanobis.
-
Which statement about squared Euclidean distance is correct?
This is why you may optimise squared error freely but must not hand squared distances to a metric tree or to any argument that invokes the triangle inequality.
pch.quizShowAnswer
B — It is not a metric — three collinear points at 0, 1 and 2 give squared distances 1, 1 and 4, and 4 exceeds 1 + 1 — but ranking by it is safe because the square root is monotone — This is why you may optimise squared error freely but must not hand squared distances to a metric tree or to any argument that invokes the triangle inequality.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – The induced norm from an arbitrary inner product
Section titled “Exercise 1 – The induced norm from an arbitrary inner product”Exercise 2 – Try to break Cauchy-Schwarz
Section titled “Exercise 2 – Try to break Cauchy-Schwarz”Exercise 3 – Show that squared distance is not a metric
Section titled “Exercise 3 – Show that squared distance is not a metric”Exercise 4 – Reproduce the metric disagreement
Section titled “Exercise 4 – Reproduce the metric disagreement”Exercise 5 – The parallelogram law tells you which norms have angles
Section titled “Exercise 5 – The parallelogram law tells you which norms have angles”Recall card
Section titled “Recall card”- The induced norm is the square root of the inner product of a vector with itself, and it is well defined precisely because the inner product is positive definite.
- Distance is the length of a difference — the same one line, applied to x minus y.
- Cauchy-Schwarz bounds the absolute inner product by the product of the two lengths, with equality exactly when the vectors are parallel; it is what makes the cosine well defined and what supplies the triangle inequality.
- A metric needs only three axioms — positive definite, symmetric, triangle inequality — and needs no vector space at all.
- Inner products sit inside norms, which sit inside metrics. The parallelogram law is the test for whether a norm has an inner product behind it, and only the Euclidean norm among the standard ones passes.
- Inner products and metrics run in opposite directions: similar means a large inner product and a small distance. Ranking by dot product equals ranking by distance only when all the vectors have equal length.
- Squared distance is not a metric — three collinear points break the triangle inequality — although ranking by it is safe.
- Changing the metric changes which point is nearest: four metrics on the same nine candidates give three different winners, and Mahalanobis nearly reverses the Euclidean ranking at the tail.
Next: Angles and Orthogonality — the second thing Cauchy-Schwarz makes possible.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading