Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsLinear Algebra

Dot product and cosine similarity

P1.B315 min●○○ BeginnerReviewed Nov 30, 2026

Why this matters for machine learning

The dot product is the most-used operation in deep learning: most of the arithmetic inside a neural network is dot products.

  • Every artificial neuron multiplies its inputs by its weights and adds them up: that's a dot product. (P4.1: From neurons to the perceptron, coming soon)
  • A neural network layer is a matrix multiplication, which is just many dot products at once. (P1.B6: Matrix multiplication)
  • Search and recommendation systems find similar items by the cosine similarity of their vectors. (P10.E4: Embedding models and semantic search, coming soon)
  • Attention, the core of every LLM, decides which words to focus on using dot products of queries and keys. (P7.3: Queries, keys and values step by step, coming soon)

Before this: Scalars, vectors and spaces, Vector operations

After this lesson you can

  • Compute the dot product of two vectors by hand
  • Read its sign as "same way", "perpendicular" or "opposite way"
  • Explain the dot product as a projection (a "shadow")
  • Find the angle between two vectors and the length of one vector's shadow on another
  • Compute cosine similarity and cosine distance, and say why they ignore length

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

2×1.5+3×0.5+1×4=3+1.5+4=8.5\begin{gathered} 2 \times 1.5 + 3 \times 0.5 + 1 \times 4 \\ \quad= 3 + 1.5 + 4 = 8.5 \end{gathered}

Put the quantities in one list, (2,3,1)(2, 3, 1), and the prices in another, (1.5,0.5,4)(1.5, 0.5, 4). 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:

a=(3,1),b=(1,2.5)⇒a⋅b=3×1+1×2.5=5.5\begin{gathered} \mathbf{a} = (3, 1), \quad \mathbf{b} = (1, 2.5) \\ \Rightarrow\quad \mathbf{a}\cdot\mathbf{b} \\ \quad= 3 \times 1 + 1 \times 2.5 = 5.5 \end{gathered}

Two vectors go in, one number comes out (a number is called a scalar). The same recipe works in any dimension: for vectors with nn entries, you add up nn products.

You will see three ways to write it. They all mean the same thing:

  • a⋅b\mathbf{a}\cdot\mathbf{b} (the “dot” that gives the operation its name),
  • a⊤b\mathbf{a}^\top\mathbf{b} (a row times a column; P1.B6 explains why this is the same),
  • ⟨a,b⟩\langle \mathbf{a}, \mathbf{b} \rangle (common in math books).

The vectors must have the same length. There is no entry to pair with if one list is longer, so (1,2,3)⋅(1,2)(1,2,3)\cdot(1,2) is not defined. NumPy raises an error in that case.

Drag the tips of a and b

−4−224−4−224θab
a = (3, 1)
b = (1, 2.5)
a·b = 3×1 + 1×2.5 = 5.5
‖a‖ = 3.16
‖b‖ = 2.69
cos θ = 0.65
θ = 49.8°

Pointing roughly the same way (angle under 90°): positive.

The thick shaded segment is the "shadow" of b on the line through a: green when it points along a, red when it points backwards.

Drag either arrow tip. The readout shows the arithmetic, and the shaded segment along a's line is b's 'shadow' on a. Keyboard: Tab to a tip, then use the arrow keys.

Play with the widget and notice three things:

When the vectors…the angle is…the dot product is…
point roughly the same wayless than 90°positive
are perpendicularexactly 90°zero
point roughly opposite waysmore 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 Rn\mathbb{R}^n the dot product has two equivalent definitions:

a⋅b=∑i=1naibi⏟algebraica⋅b=∥a∥ ∥b∥cos⁡θ⏟geometric\begin{gathered} \underbrace{\mathbf{a}\cdot\mathbf{b} = \sum_{i=1}^{n} a_i b_i}_{\text{algebraic}} \\ \underbrace{\mathbf{a}\cdot\mathbf{b} = \|\mathbf{a}\|\,\|\mathbf{b}\|\cos\theta}_{\text{geometric}} \end{gathered}

Here ∥a∥=a⋅a\|\mathbf{a}\| = \sqrt{\mathbf{a}\cdot\mathbf{a}} is the length (norm) of a\mathbf{a} (P1.B4 studies norms) and θ\theta is the angle between the vectors, between 0°0° and 180°180°.

The angle. Solve the geometric formula for θ\theta:

θ=arccos⁡ ⁣(a⋅b∥a∥ ∥b∥)\theta = \arccos\!\left(\frac{\mathbf{a}\cdot\mathbf{b}}{\|\mathbf{a}\|\,\|\mathbf{b}\|}\right)

For a=(3,1)\mathbf{a}=(3,1) and b=(1,2.5)\mathbf{b}=(1,2.5): ∥a∥≈3.162\|\mathbf{a}\|\approx 3.162, ∥b∥≈2.693\|\mathbf{b}\|\approx 2.693, so cos⁡θ≈5.5/(3.162×2.693)≈0.646\cos\theta \approx 5.5/(3.162 \times 2.693) \approx 0.646 and θ≈49.8°\theta \approx 49.8°. The function arccos⁡\arccos returns an angle from 0°0° to 180°180°, 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 a\mathbf{a} is the scalar projection:

∥b∥cos⁡θ=a⋅b∥a∥\|\mathbf{b}\|\cos\theta = \frac{\mathbf{a}\cdot\mathbf{b}}{\|\mathbf{a}\|}

Here it is 5.5/3.162≈1.7395.5 / 3.162 \approx 1.739. (Projecting onto whole planes and subspaces is P1.B11.)

Properties. For vectors a,b,c\mathbf{a},\mathbf{b},\mathbf{c} and a number kk:

  • Symmetric: a⋅b=b⋅a\mathbf{a}\cdot\mathbf{b} = \mathbf{b}\cdot\mathbf{a}
  • Distributes over addition: a⋅(b+c)=a⋅b+a⋅c\mathbf{a}\cdot(\mathbf{b}+\mathbf{c}) = \mathbf{a}\cdot\mathbf{b} + \mathbf{a}\cdot\mathbf{c}
  • Scales: (ka)⋅b=k (a⋅b)(k\mathbf{a})\cdot\mathbf{b} = k\,(\mathbf{a}\cdot\mathbf{b})
  • Length from a dot product: a⋅a=∥a∥2\mathbf{a}\cdot\mathbf{a} = \|\mathbf{a}\|^2, which is never negative, and is 00 only for the zero vector.

Two things that do NOT hold.

  • There is no “associative” rule: (a⋅b)⋅c(\mathbf{a}\cdot\mathbf{b})\cdot\mathbf{c} is not even defined: a⋅b\mathbf{a}\cdot\mathbf{b} is a number, and you cannot take the dot product of a number with a vector.
  • You cannot cancel. a⋅b=a⋅c\mathbf{a}\cdot\mathbf{b} = \mathbf{a}\cdot\mathbf{c} does not mean b=c\mathbf{b}=\mathbf{c}. Example: (1,0)⋅(2,5)=2=(1,0)⋅(2,−7)(1,0)\cdot(2,5) = 2 = (1,0)\cdot(2,-7).

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 out

In 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 (1,2,2)(1, 2, 2) and (2,−2,1)(2, -2, 1):

1×2+2×(−2)+2×1=2−4+2=0\begin{gathered} 1 \times 2 + 2 \times (-2) + 2 \times 1 \\ \quad= 2 - 4 + 2 = 0 \end{gathered}

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 a\mathbf{a}, b\mathbf{b} and a−b\mathbf{a}-\mathbf{b}:

∥a−b∥2=∥a∥2+∥b∥2−2∥a∥∥b∥cos⁡θ\begin{aligned} \|\mathbf{a}-\mathbf{b}\|^2 &= \|\mathbf{a}\|^2 + \|\mathbf{b}\|^2 \\ &\quad - 2\|\mathbf{a}\|\|\mathbf{b}\|\cos\theta \end{aligned}

Now expand the left side using the algebraic definition and the properties above:

∥a−b∥2=(a−b)⋅(a−b)=∥a∥2−2 a⋅b+∥b∥2\begin{aligned} \|\mathbf{a}-\mathbf{b}\|^2 &= (\mathbf{a}-\mathbf{b})\cdot(\mathbf{a}-\mathbf{b}) \\ &= \|\mathbf{a}\|^2 - 2\,\mathbf{a}\cdot\mathbf{b} + \|\mathbf{b}\|^2 \end{aligned}

Set the two equal and cancel: a⋅b=∥a∥∥b∥cos⁡θ\mathbf{a}\cdot\mathbf{b} = \|\mathbf{a}\|\|\mathbf{b}\|\cos\theta.

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:

cosine similarity(a,b)=a⋅b∥a∥ ∥b∥=cos⁡θ\begin{gathered} \text{cosine similarity}(\mathbf{a}, \mathbf{b}) \\ \quad= \frac{\mathbf{a}\cdot\mathbf{b}}{\|\mathbf{a}\|\,\|\mathbf{b}\|} = \cos\theta \end{gathered}

How to read it:

ValueMeaning
11same direction
00perpendicular
−1-1opposite directions

It always lies between −1-1 and 11. Three more facts:

  • Positive scaling changes nothing. Replace a\mathbf{a} by 3a3\mathbf{a} and the cosine is the same. Scale by a negative number and the sign flips: −a-\mathbf{a} points the opposite way, so its cosine with b\mathbf{b} 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 1−cosine similarity1 - \text{cosine similarity}. 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):

wordvector
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°).

Try it: cosine similarity in NumPy

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: a^=a/∥a∥\hat{\mathbf{a}} = \mathbf{a}/\|\mathbf{a}\|. This is called normalizing, and it keeps the direction.

For unit vectors both lengths in the cosine formula are 1, so

cos⁡θ=a^⋅b^\cos\theta = \hat{\mathbf{a}}\cdot\hat{\mathbf{b}}

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

Angle, shadow, unit vectors and mistakes

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 cos⁡θ\cos\theta 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 [−1,1][-1, 1]. Here is a proof from the algebraic definition.

Take any a≠0\mathbf{a}\ne\mathbf{0} and let t=a⋅b∥a∥2t = \dfrac{\mathbf{a}\cdot\mathbf{b}}{\|\mathbf{a}\|^2}. A squared length is never negative, so

0≤∥b−ta∥2=∥b∥2−2t a⋅b+t2∥a∥2=∥b∥2−(a⋅b)2∥a∥2\begin{gathered} 0 \le \|\mathbf{b} - t\mathbf{a}\|^2 \\ \quad= \|\mathbf{b}\|^2 - 2t\,\mathbf{a}\cdot\mathbf{b} + t^2\|\mathbf{a}\|^2 \\ \quad= \|\mathbf{b}\|^2 - \frac{(\mathbf{a}\cdot\mathbf{b})^2}{\|\mathbf{a}\|^2} \end{gathered}

Rearranging gives the Cauchy–Schwarz inequality:

∣a⋅b∣≤∥a∥ ∥b∥|\mathbf{a}\cdot\mathbf{b}| \le \|\mathbf{a}\|\,\|\mathbf{b}\|

Divide both sides by ∥a∥∥b∥\|\mathbf{a}\|\|\mathbf{b}\| (both non-zero) and you get ∣cos⁡θ∣≤1|\cos\theta|\le 1. So arccos⁡\arccos is always defined, and the angle is a real number between 0°0° and 180°180° 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, ∥a^∥=∥b^∥=1\|\hat{\mathbf{a}}\|=\|\hat{\mathbf{b}}\|=1, so

∥a^−b^∥2=∥a^∥2−2 a^⋅b^+∥b^∥2=2−2cos⁡θ\begin{aligned} \|\hat{\mathbf{a}}-\hat{\mathbf{b}}\|^2 &= \|\hat{\mathbf{a}}\|^2 - 2\,\hat{\mathbf{a}}\cdot\hat{\mathbf{b}} + \|\hat{\mathbf{b}}\|^2 \\ &= 2 - 2\cos\theta \end{aligned}

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 a=(0.6,0.8)\mathbf{a}=(0.6,0.8) and b=(0.8,0.6)\mathbf{b}=(0.8,0.6), both of length 1: the cosine is 0.960.96, and ∥a−b∥2=0.08=2−2×0.96\|\mathbf{a}-\mathbf{b}\|^2 = 0.08 = 2 - 2\times 0.96. (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 1/n1/\sqrt{n} as the dimension nn 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

  1. What is (2,−1)⋅(3,4)(2, -1) \cdot (3, 4)?

  2. Two non-zero vectors have a dot product of 00. What does that tell you?

  3. You double the length of a\mathbf{a} without changing its direction. What happens?

  4. Which value is impossible for cosine similarity?

  5. The cosine similarity of a\mathbf{a} and b\mathbf{b} is 0.60.6. What is the cosine similarity of −2a-2\mathbf{a} and b\mathbf{b}?

Exercises

  1. 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.
  2. Compute (1,2,3)⋅(4,−5,6)(1, 2, 3)\cdot(4, -5, 6) by hand.
    Show answer4 − 10 + 18 = 12.
  3. Find a vector perpendicular to (2,5)(2, 5). (Hint: swap the entries and flip one sign.)
    Show answerfor example (5, −2), because 2×5 + 5×(−2) = 0.
  4. Find the angle between (1,0)(1, 0) and (1,1)(1, 1).
    Show answerthe dot product is 1, the lengths are 1 and √2, so cos θ = 1/√2 ≈ 0.707 and θ = 45°.
  5. Find the length of the shadow of b=(2,1)\mathbf{b}=(2,1) on a=(3,4)\mathbf{a}=(3,4).
    Show answera·b = 10 and ‖a‖ = 5, so the scalar projection is 10 / 5 = 2.
  6. Normalize (3,4)(3, 4), then compute its dot product with (0.8,0.6)(0.8, 0.6).
    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°.
  7. What is the cosine similarity of (1,2,3)(1, 2, 3) with (2,4,6)(2, 4, 6), and with (−1,−2,−3)(-1, -2, -3)?
    Show answer1 and −1. The second vector is 2 times the first; the third is −1 times it.
  8. 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 try cosine(cat, np.zeros(3)) to see what happens with the zero vector.
    Show answeryou get a division by zero, so the result is nan; NumPy also prints a warning.

Key takeaways

  • The dot product multiplies matching entries and adds them up: a·b = a₁b₁ + a₂b₂ + …. The result is a single number.
  • Positive means the vectors point roughly the same way, zero means perpendicular, negative means roughly opposite.
  • Geometrically, a·b = ‖a‖ ‖b‖ cos θ: the length of a times the length of b's shadow on a.
  • Cosine similarity divides out both lengths, leaving only direction. It always lies between −1 and 1, and it is undefined for the zero vector.
  • Cosine distance is 1 − cosine similarity. For unit vectors (length 1) the dot product already is the cosine.
  • The dot product is not the element-wise product: for 1-D NumPy arrays, a * b gives a vector and a @ b gives the dot product.
  • Neurons, matrix multiplication, embedding search and attention are all built from dot products.
Found a mistake? Tell us