Search engines, recommendation systems and large language models all ask the same question, millions of times a second: how similar are these two things? When the things are vectors (lists of numbers), the answer starts with one simple operation.
An everyday example: a shopping bill
You buy 2 apples at 1.50 each, 3 bananas at 0.50 each and 1 melon at 4.00. The total bill is
Put the quantities in one list, , and the prices in another, . Multiply matching entries, then add. That is a weighted sum, and it is exactly the dot product of the two lists. A neural network neuron does the same thing: it multiplies each input by a weight (how much that input matters) and adds the results up.
The recipe
Take two vectors of the same length. Multiply matching entries, then add the results:
Two vectors go in, one number comes out (a number is called a scalar). The same recipe works in any dimension: for vectors with entries, you add up products.
You will see three ways to write it. They all mean the same thing:
- (the “dot” that gives the operation its name),
- (a row times a column; P1.B6 explains why this is the same),
- (common in math books).
The vectors must have the same length. There is no entry to pair with if one list is longer, so is not defined. NumPy raises an error in that case.
Play with the widget and notice three things:
| When the vectors… | the angle is… | the dot product is… |
|---|---|---|
| point roughly the same way | less than 90° | positive |
| are perpendicular | exactly 90° | zero |
| point roughly opposite ways | more than 90° | negative |
(Perpendicular is also called orthogonal. The widget only says “Perpendicular” when the dot product is exactly 0. When the angle is within about 1° of 90° but the dot product isn’t exactly 0, it says “Almost perpendicular”.)
Also notice that making either arrow longer makes the dot product bigger in size: more positive, or more negative. Perpendicular arrows stay at 0 however long they are. Hold on to this; it matters for cosine similarity below.
What the number means
Intuition
Shine a light straight down onto the line through a. Vector b casts a shadow on that line (the shaded segment in the widget).
The dot product is the length of a times the signed length of b’s shadow. “Signed” means that if the shadow points backwards along a, its length counts as negative. If b is perpendicular to a, the shadow has no length at all, so the dot product is zero.
That is why the dot product measures agreement: it is large when b points a lot in the direction of a.
The analogy has one weak spot: a real shadow cannot be negative, but this one can. And the shadow is only half the story, because the dot product also multiplies by the length of a.
Math
For vectors in the dot product has two equivalent definitions:
Here is the length (norm) of (P1.B4 studies norms) and is the angle between the vectors, between and .
The angle. Solve the geometric formula for :
For and : , , so and . The function returns an angle from to , which is exactly the range of angles between two vectors.
The shadow, as a formula. The signed length of b’s shadow on the line through is the scalar projection:
Here it is . (Projecting onto whole planes and subspaces is P1.B11.)
Properties. For vectors and a number :
- Symmetric:
- Distributes over addition:
- Scales:
- Length from a dot product: , which is never negative, and is only for the zero vector.
Two things that do NOT hold.
- There is no “associative” rule: is not even defined: is a number, and you cannot take the dot product of a number with a vector.
- You cannot cancel. does not mean . Example: .
Code
import numpy as np
a = np.array([3.0, 1.0])
b = np.array([1.0, 2.5])
np.dot(a, b) # 5.5
a @ b # 5.5, the @ operator does the same
(a * b).sum() # 5.5, the recipe written outIn PyTorch it is torch.dot(a, b) or a @ b. Careful: a * b is not the dot product. It multiplies entry by entry and gives the vector [3. , 2.5]. The dot product is that vector’s sum.
It works in any dimension
You cannot draw 3-D or 300-D arrows on a flat screen, but the recipe and the sign rule still work. Take and :
The dot product is 0, so these two 3-D vectors are perpendicular. Real embeddings have hundreds or thousands of entries; the dot product is how we measure angles there.
Go deeper Why do the two definitions agree? (law of cosines)
Apply the law of cosines to the triangle with sides , and :
Now expand the left side using the algebraic definition and the properties above:
Set the two equal and cancel: .
This argument draws a triangle, so it is a picture in 2-D or 3-D. In higher dimensions any two vectors still lie in a flat 2-D plane, and the same triangle lives inside it. (In 300-D you can also simply take the formula as the definition of the angle; the next box shows it always gives a valid number.)
Cosine similarity: direction only
The dot product mixes two things: how aligned the vectors are, and how long they are. Often we only care about the first. A long document and a short one about the same topic should count as similar.
The fix is to divide out both lengths:
How to read it:
| Value | Meaning |
|---|---|
| same direction | |
| perpendicular | |
| opposite directions |
It always lies between and . Three more facts:
- Positive scaling changes nothing. Replace by and the cosine is the same. Scale by a negative number and the sign flips: points the opposite way, so its cosine with is the negative of the original.
- The zero vector has no direction, so cosine similarity with it is undefined (the formula would divide by 0). Code that computes cosines must handle this case.
- Cosine distance is . It is 0 for identical directions, 1 for perpendicular, 2 for opposite. Many libraries use it so that “smaller means closer”, like a distance.
Worked example: toy word vectors
Suppose a model describes words with three numbers (real models use hundreds or thousands; these are made up to keep the arithmetic small):
| word | vector |
|---|---|
| cat | (0.9, 0.8, 0.1) |
| dog | (0.8, 0.9, 0.2) |
| car | (0.1, 0.2, 0.9) |
cat · dog = 0.9×0.8 + 0.8×0.9 + 0.1×0.2 = 0.72 + 0.72 + 0.02 = 1.46
Lengths: ‖cat‖ = √(0.81 + 0.64 + 0.01) ≈ 1.208 and ‖dog‖ = √(0.64 + 0.81 + 0.04) ≈ 1.221
cosine(cat, dog) = 1.46 / (1.208 × 1.221) ≈ 0.99: almost the same direction (about 8°). Its cosine distance is about 0.01.
Do the same for cat and car: the dot product is 0.34, ‖car‖ ≈ 0.927, so cosine(cat, car) ≈ 0.34 / (1.208 × 0.927) ≈ 0.30: much less similar (about 72°).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Unit vectors: normalize once, then use the dot product
A unit vector has length 1. You can turn any non-zero vector into one by dividing it by its own length: . This is called normalizing, and it keeps the direction.
For unit vectors both lengths in the cosine formula are 1, so
For unit vectors, the dot product is the cosine similarity. This is why many search systems normalize every embedding once, when they store it. After that, comparing a query with a million stored vectors needs only plain dot products, which are cheap and fast.
Using the dot product in code
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Go deeper Why is cosine always between −1 and 1? (Cauchy–Schwarz)
If were defined by the geometric formula in a picture, the bound would be automatic. In high dimensions we want to be sure the ratio can never leave . Here is a proof from the algebraic definition.
Take any and let . A squared length is never negative, so
Rearranging gives the Cauchy–Schwarz inequality:
Divide both sides by (both non-zero) and you get . So is always defined, and the angle is a real number between and in any dimension. Equality holds exactly when one vector is a multiple of the other.
Go deeper Ranking by cosine = ranking by distance (for unit vectors)
For unit vectors, , so
A larger cosine means a smaller distance. So the item with the highest cosine similarity to a query is also the nearest item by ordinary straight-line distance, and the two methods give the same ranking. Check with and , both of length 1: the cosine is , and . (This holds only after normalizing. For vectors of different lengths, the two rankings can differ. P1.B4 covers distances.)
Go deeper Random vectors in high dimensions are almost perpendicular
Pick two vectors at random in a high-dimensional space, with independent random entries centred on zero (for example from a standard normal distribution, np.random.randn). Their cosine tends to be close to 0, and the typical size of that cosine shrinks roughly like as the dimension grows. So in hundreds or thousands of dimensions, two random directions are nearly perpendicular.
The “centred on zero” part matters. With all-positive entries, such as np.random.rand (uniform between 0 and 1), every vector leans toward the same corner of the space, and the cosine settles near 0.75 instead of 0.
This is a statement about random vectors, not about every vector (the vectors in your data are not random). It helps explain two things: why a high cosine between real embeddings is meaningful (chance alone rarely produces one), and why such spaces have room for very many directions that barely interfere with each other.
Check your understanding
What is ?
2 × 3 + (−1) × 4 = 6 − 4 = 2. A dot product is always a single number, never a vector. The vector (6, −4) is the element-wise product, which is a different operation.
Two non-zero vectors have a dot product of . What does that tell you?
Since a·b = ‖a‖‖b‖ cos θ and neither length is zero, cos θ must be 0, so θ = 90°. Length plays no part: two very long vectors can also have a dot product of 0.
You double the length of without changing its direction. What happens?
The dot product scales with length: (2a)·b = 2(a·b). Cosine similarity divides by ‖a‖, so the factor of 2 cancels out.
Which value is impossible for cosine similarity?
Cosine similarity equals cos θ, which always lies between −1 and 1 (Cauchy–Schwarz shows this holds in every dimension).
The cosine similarity of and is . What is the cosine similarity of and ?
The factor 2 cancels, as it does for any positive scaling. The minus sign flips the vector to point the opposite way, so the cosine changes sign. The values −1.2 and 1.2 are impossible, because a cosine is never outside −1 to 1.
Exercises
- A basket has 4 pens at 2 each, 1 notebook at 5 and 2 erasers at 0.5. Write the bill as a dot product and compute it.
Show answer
(4, 1, 2)·(2, 5, 0.5) = 8 + 5 + 1 = 14. - Compute by hand.
Show answer
4 − 10 + 18 = 12. - Find a vector perpendicular to . (Hint: swap the entries and flip one sign.)
Show answer
for example (5, −2), because 2×5 + 5×(−2) = 0. - Find the angle between and .
Show answer
the dot product is 1, the lengths are 1 and √2, so cos θ = 1/√2 ≈ 0.707 and θ = 45°. - Find the length of the shadow of on .
Show answer
a·b = 10 and ‖a‖ = 5, so the scalar projection is 10 / 5 = 2. - Normalize , then compute its dot product with .
Show answer
(3, 4)/5 = (0.6, 0.8); the dot product is 0.48 + 0.48 = 0.96, which is the cosine of the angle between them, about 16.3°. - What is the cosine similarity of with , and with ?
Show answer
1 and −1. The second vector is 2 times the first; the third is −1 times it. - In the code cell, add a vector for “truck” that should be close to “car” and far from “cat”. Check it with
cosine, and also trycosine(cat, np.zeros(3))to see what happens with the zero vector.Show answer
you get a division by zero, so the result isnan; NumPy also prints a warning.