Chapter 2: Dot product, length and angle

Previous: LA 01 Vectors and Linear Combinations | LA 00 Course Map | Next: LA 03 Matrices as Linear Maps

The big idea

The dot product takes two vectors and returns one number that measures how much they point the same way. From that single operation you get length, distance, angle, perpendicularity and projection.

In this chapter you will learn to
  1. Compute a dot product, and know its algebraic rules.
  2. Compute the length of a vector and the distance between two points.
  3. Find the angle between two vectors, and test whether they are perpendicular.
  4. Use cosine similarity to compare directions.
  5. Project one vector onto another, and explain why the formula works.
Before you start

You need vectors, addition and scaling from LA 01 Vectors and Linear Combinations. You also need two facts from school geometry: Pythagoras’ theorem ( for a right triangle) and the meaning of cosine (, , ).


2.1 The dot product

Why we need it

Chapter 1 gave us ways to build vectors. It said nothing about measuring them. How long is a vector? Do two vectors point in similar directions? Are they at right angles? All of these questions are answered by one tool.

The definition

Definition: dot product

For two vectors of the same size, ,

Multiply matching entries, then add everything up.

You will also see it written (a row times a column, explained in chapter 3) or . All three notations mean the same thing.

The result is a number, not a vector

Adding vectors gives a vector. Scaling gives a vector. The dot product gives a single number (a scalar). This is the first operation in the course that does that.

Worked example 2.1.

Worked example 2.2.

Keep that zero in mind. It turns out to mean these two vectors are at right angles (section 2.4).

Worked example 2.3: a dot product as a weighted total. You buy 3 apples at 0.50, 2 loaves at 1.20 and 5 eggs at 0.25. Put the quantities in and the prices in . The total bill is

This is the most common everyday reading: a dot product is a weighted sum. One vector holds amounts; the other holds what each amount is worth.

Rules

Each of these comes straight from the definition by looking at the sum term by term.

RuleFormulaWhy
symmetric
distributive
scalars come out
positive, and only if , a sum of squares

These let you expand dot products like ordinary brackets:

This expansion is used in the proof in section 2.3, so make sure you can derive it: distribute the left bracket over the right, giving , then use symmetry to combine the middle terms.


2.2 Length and distance

Length from Pythagoras

How long is the arrow ? It goes 3 across and 4 up. Those two moves are the two short sides of a right triangle, and the arrow is the long side. By Pythagoras,

Notice that is exactly . That is no accident.

Definition: length (norm)

The length or norm of is

The double bars distinguish it from the absolute value of a single number, although for a 1-entry vector the two agree.

In 3-D, Pythagoras is used twice. For : the floor diagonal under the arrow has length . The arrow rises 2 above the end of that diagonal, so its length is . The formula just adds all the squares at once, in any dimension.

Worked example 2.4. .

Worked example 2.5. . In , the all-ones vector has length , which grows with dimension. This is one reason distances behave strangely in very high dimensions.

Scaling and length

Scaling a vector by scales its length by :

Why: . The absolute value appears because ; a negative scale flips direction but cannot make a length negative.

Unit vectors

Definition: unit vector

A unit vector has length 1. To turn any nonzero into a unit vector pointing the same way, divide by its length:

This is called normalizing .

Worked example 2.6. , , so . Check: .

Unit vectors describe pure direction, with the size stripped away. A robot “approach direction” or a camera’s viewing direction is a unit vector.

Distance

The distance between two points and is the length of the arrow joining them, which (chapter 1) is :

Worked example 2.7. Points and : difference , distance .


2.3 The angle between two vectors

The key formula

Geometric meaning of the dot product

where is the angle between the two arrows (between and ).

Read it as: the dot product is the product of the lengths, multiplied by a factor that measures alignment. That factor, , is 1 when the vectors point the same way and shrinks as they turn apart.

Rearranged, it gives a way to compute angles:

Why the formula is true

This proof uses only the dot product rules from section 2.1 and the law of cosines from trigonometry. The law of cosines says that in a triangle with sides , , , where is the angle between sides and :

(When , and this is Pythagoras.)

Step 1: draw the triangle. Put and tail to tail at the origin. The third side joins their tips, and from chapter 1 that side is .

Step 2: apply the law of cosines with , , :

Step 3: expand the left side with dot products. Since ,

Step 4: compare. Both lines equal . Cancel from both, then divide by :

Reading the sign of a dot product

Lengths are always positive, so the sign of is the sign of :

AngleMeaning
positiveless than roughly the same direction
zeroexactly perpendicular
negativemore than roughly opposite directions

Worked example 2.8. Angle between and :

  • ,
  • , so .

That matches the picture: points along the diagonal, halfway between the axes.

Worked example 2.9. Angle between and :

  • ,
  • , so .

Worked example 2.10. Angle between and : dot product , lengths each, , so . Exactly opposite, as expected.


2.4 Perpendicular (orthogonal) vectors

Definition: orthogonal

Two vectors and are orthogonal (perpendicular) when

In 2-D and 3-D this matches the usual right angle, because . In higher dimensions there is no picture, so this equation is the definition. That is a common pattern in linear algebra: a geometric idea from 2-D becomes an algebraic definition that works everywhere.

By this definition the zero vector is orthogonal to every vector. That is a harmless convention.

Worked example 2.11. Find all vectors orthogonal to . We need with , that is . All multiples of work. In 2-D, the perpendicular directions to a given vector form a line.

Worked example 2.12. Find so that is orthogonal to . We need , so .

Worked example 2.13: a useful trick. In 2-D, is always orthogonal to , since . Swapping entries and negating one rotates a vector by .

Pythagoras in any dimension

If and are orthogonal, the cross term in the expansion vanishes:

That is Pythagoras’ theorem, now proved in any number of dimensions. It will be the key step in least squares (LA 06 Orthogonality and Least Squares).


2.5 Cosine similarity

Sometimes you care only about direction, not size. Two documents might use the same words in the same proportions, but one is twice as long. Two camera images might show the same scene at different brightness.

Divide out the lengths and you get a pure alignment score:

Definition: cosine similarity
ValueMeaning
identical direction
unrelated (perpendicular)
opposite direction

Worked example 2.14. Word counts for the words (robot, learning, cake): document A , document B , document C .

  • . Same topic; B is just shorter.
  • . Almost unrelated.

Why it is always between and

That fact is the Cauchy-Schwarz inequality:

In 2-D and 3-D it follows from . In general, here is a proof that does not need angles.

Proof. If both sides are 0. Otherwise, for every real number , the length squared of cannot be negative:

The right side is a quadratic in that never goes below zero. Choose the at its minimum, . Substituting:

Multiply by and rearrange: . Take square roots.

Equality holds exactly when , that is when and lie on the same line.

The triangle inequality

A close relative:

In words: walking along then can never be shorter than going straight to the end. Proof: , using Cauchy-Schwarz in the middle step.


2.6 Projection: the shadow of one vector on another

The question

How much of points in the direction of ? Imagine light shining straight down onto the line through . The shadow that casts on that line is the projection of onto .

            b
           /|
          / |
         /  |  e = b - p   (perpendicular to a)
        /   |
       /    |
 -----●-----●---------> a
   origin   p  (projection)

Deriving the formula

We do not memorize this formula; we build it from one idea.

Step 1. The shadow lies on the line through , so it is a multiple of :

Step 2. The leftover piece (the “error”, from the tip of the shadow up to ) must be perpendicular to . That is what “shining straight down” means:

Step 3. Expand using the dot product rules:

Step 4. So:

Projection formula

If is a unit vector, and this simplifies to .

The last line says something important: dotting with a unit vector measures how far you go in that direction. is the signed length of the shadow.

Worked examples

Worked example 2.15. Project onto .

  • , , so and .
  • Leftover . Check: . ✓

That matches intuition: the shadow on the horizontal axis keeps only the horizontal part.

Worked example 2.16. Project onto .

  • , , so and .
  • Leftover .
  • Check: . ✓

So splits into two perpendicular pieces: along and across it.

Worked example 2.17: a physical reading. A force newtons pushes a cart that can only roll along the unit direction . Only the component along the track does useful work: newtons. The 4 newtons pushing sideways do nothing to move the cart. Work done over a displacement is exactly .

Splitting any vector into two perpendicular parts

Projection always splits into

And because , Pythagoras (section 2.4) gives . In example 2.16: , , . ✓

Why this matters later

is the point on the line through that is closest to . Any other point on the line is further away, by Pythagoras again. Hold on to this: least squares in chapter 6 is this exact argument, with a whole plane (or higher-dimensional space) in place of the line.


Summary

IdeaFormulaRemember it as
dot productmultiply matching entries, add
lengthPythagoras
unit vectordirection only
distancelength of the gap
anglealignment score
orthogonalright angle
projectionshadow; leftover is perpendicular

Three facts to remember:

  1. A dot product is one number: a weighted sum, and an alignment score.
  2. Zero dot product means perpendicular, in any dimension.
  3. Projection is found by demanding that the leftover is perpendicular.

Exercises

Part A: warm-up

A1. Compute .

A2. Find the length of and the unit vector in its direction.

A3. Find the distance between and .

A4. Find the angle between and .

A5. Are and orthogonal?

Part B: core

B1. Find all values of for which and are orthogonal.

B2. Find a unit vector orthogonal to both and .

B3. Project onto . Write as the sum of a part along and a part perpendicular to , and check that the second part really is perpendicular.

B4. A robot gripper approaches along the unit direction (straight down). The object’s surface normal is . Find the angle between and . Is the approach close to head-on?

B5. Using cosine similarity, which of the vectors , , is most similar in direction to ? Which is least similar?

B6. Show by example that does not imply . (So you cannot “cancel” from a dot product.)

Part C: explain and prove

C1. Prove that .

C2. Prove the parallelogram law: . Describe what it says about the diagonals of a parallelogram.

C3. Prove that if is orthogonal to both and , then is orthogonal to every linear combination .

C4. Explain why holds only when and point in the same direction (or one is zero).

C5. Using the projection formula, prove that the leftover is orthogonal to . (That is, check the derivation works.)

Part D: practise with code

D1. In NumPy, np.dot(u, v) (or u @ v) computes a dot product and np.linalg.norm(v) a length. Recompute worked examples 2.1, 2.9 and 2.16.

D2. Write angle_deg(u, v) returning the angle in degrees. Use np.clip on the cosine before np.arccos. Why is the clip needed?

D3. Write project(b, a) and perp(b, a). Test that project(b, a) + perp(b, a) equals b and that perp(b, a) @ a is (nearly) zero.

D4 (high dimensions). Draw two random vectors with 1000 entries each from a standard normal (np.random.randn(1000)). Compute their cosine similarity. Repeat 100 times and look at the values. What do you notice, and why might that be?


Where this is used

  • Neurons. A neuron computes : how well the input aligns with a learned direction (05 Training Neural Policies).
  • Attention. Attention scores in transformers are dot products between “query” and “key” vectors (Appendix - Neural Networks and Attention).
  • Loss functions. Mean squared error is a squared distance divided by the number of entries.
  • Grasping. Comparing an approach direction with a surface normal is a dot product between unit vectors.

Next: LA 03 Matrices as Linear Maps, where we start transforming vectors.