The Dot Product
The dot product multiplies two vectors and returns a single number. That number measures how much the vectors point the same way: it gives angles, tests for perpendicularity, and computes projections. In software it is probably the most executed formula there is: lighting in every 3D game and similarity search in every LLM application run on it.
The definition
For and :
Multiply matching components and add. The result is a scalar, which is why it is also called the scalar product or inner product.
Algebraic rules
| Rule | Formula |
|---|---|
| symmetric | |
| distributive | |
| scalars pull out | |
| length | , so for |
The last rule connects dot product and length: .
The geometric meaning: angles
For non-zero vectors with angle between them ():
Why: the law of cosines for the triangle with sides , and says . Expanding the left side with the rules above gives . Comparing the two expressions gives .
| Sign of | Angle | Meaning |
|---|---|---|
| positive | roughly the same direction | |
| zero | orthogonal (perpendicular) | |
| negative | roughly opposite |
import numpy as np
def angle_deg(u, v):
c = np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v))
return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
u = np.array([1.0, 1.0, 0.0])
print("u . v =", np.dot(u, [1.0, 0.0, 0.0]), " angle:", round(angle_deg(u, [1, 0, 0]), 4))
print("angle to (1,-1,5):", angle_deg(u, np.array([1.0, -1.0, 5.0])))
print("angle to (-2,-2,0):", angle_deg(u, np.array([-2.0, -2.0, 0.0])))u . v = 1.0 angle: 45.0
angle to (1,-1,5): 90.0
angle to (-2,-2,0): 179.99999879258172
The last result should be exactly 180°. Near , arccos is extremely sensitive: a rounding error of about in the cosine becomes about degrees in the angle. np.clip guards against rounding pushing the cosine slightly beyond , which would make arccos return NaN. Robust geometry code computes angles as instead (see Game Math: Angle Between).
Cauchy–Schwarz and the triangle inequality
Since , we get the Cauchy–Schwarz inequality , valid in every (it can also be proved purely algebraically, without angles, which is how one justifies the definition of angle in ). It implies the triangle inequality:
Projection
The projection of onto a non-zero vector is the "shadow" of along :
The leftover is orthogonal to . Projections split a vector into "along " and "across "; games use them to slide along walls, and they lead to least squares later.
In software: lighting, culling and similarity
import numpy as np
def unit(v):
v = np.asarray(v, dtype=float)
return v / np.linalg.norm(v)
# 1) Lambert diffuse lighting: brightness = max(0, n . l)
light = unit([1, 2, 2]) # direction towards the light
for name, n in [("facing up", [0, 0, 1]), ("tilted", [1, 0, 1]), ("facing away", [0, 0, -1])]:
print(f"{name:11s} brightness = {max(0.0, float(np.dot(unit(n), light))):.3f}")
# 2) back-face culling: skip triangles whose normal points away from the camera
camera_dir = np.array([0.0, 0.0, -1.0]) # camera looks down -z
for n in ([0, 0, 1], [0, 0, -1]):
visible = np.dot(n, camera_dir) < 0
print("normal", n, "visible" if visible else "culled")facing up brightness = 0.667
tilted brightness = 0.707
facing away brightness = 0.000
normal [0, 0, 1] visible
normal [0, 0, -1] culled
- Diffuse lighting (Lambert's cosine law): a surface is brightest when its unit normal points straight at the light, and the brightness falls off as . Negative values mean the light is behind the surface, so they are clamped to 0.
- Back-face culling: a triangle whose normal points away from the viewer () cannot be seen on a closed mesh, so the GPU skips it, roughly halving the work. The normal itself comes from the cross product.
Cosine similarity in ML and LLMs is the cosine of the angle between two vectors:
import numpy as np
def cos_sim(a, b):
return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
# toy 4-dimensional "embeddings" (real ones have hundreds of dimensions)
emb = {
"cat": np.array([0.9, 0.8, 0.1, 0.0]),
"kitten": np.array([0.8, 0.9, 0.2, 0.1]),
"car": np.array([0.1, 0.0, 0.9, 0.8]),
}
for a, b in [("cat", "kitten"), ("cat", "car"), ("kitten", "car")]:
print(f"{a:6s} vs {b:6s}: {cos_sim(emb[a], emb[b]):.3f}")cat vs kitten: 0.987
cat vs car : 0.123
kitten vs car : 0.230
Semantic search and retrieval-augmented generation rank documents by exactly this number; with vectors pre-normalized to length 1 it is just a dot product. More in Embeddings and Cosine Similarity and Vector Search. A neural network's dense layer is a stack of dot products too: each output is .
See also Dot and Cross Products, The Dot Product (in depth) and Game Math: Dot Product.
Exercises
Exercise 1: Compute and classify
Compute and say whether the angle is acute, right or obtuse: (a) , ; (b) , ; (c) , .
Answer
(a) 0, right angle; (b) 0, right angle; (c) −5, obtuse.
Solution
Exercise 2: An angle
Find the angle between and .
Answer
60°.
Solution
Exercise 3: Projection
Project onto and onto . Check that is orthogonal to .
Answer
; ; the remainder is orthogonal to .
Solution
Exercise 4: Make it orthogonal
Find so that is orthogonal to .
Answer
.
Solution
Exercise 5: Most similar document (code)
Given a query vector and documents , , , rank the documents by cosine similarity to .
Answer
(0.943), (0.707), (0.000).
Solution
import numpy as np
q = np.array([1, 0, 1, 0])
docs = {"d1": [2, 0, 2, 1], "d2": [0, 1, 0, 1], "d3": [1, 1, 1, 1]}
scores = {k: float(np.dot(q, d) / (np.linalg.norm(q) * np.linalg.norm(d))) for k, d in docs.items()}
for k in sorted(scores, key=scores.get, reverse=True):
print(k, round(scores[k], 3))d1 0.943
d3 0.707
d2 0.0
Test yourself
What is ?
- 0
- 12
- -6
In Lambert lighting, why is used instead of ?
- To normalize the vectors
- A negative value means the light is behind the surface, which should be dark, not negative
- To speed up the computation
- Because is always negative
For unit vectors and , the cosine similarity equals…
- the angle in degrees