Mathematical Foundations

II.4 · Linear Algebra

How much do two directions agree?

Turn two vectors and inspect the sign of their dot product. Component multiplication and an angle describe the same alignment, while the parallel part previews projection.

Turn two vectors; read their alignment

A positive dot product means an acute angle: the directions partly agree.

first direction
(3, 0)
second vector
(2, 2)
signed component along u
6 / (3)2
dot product
6
first component product
6
second component product
0
angle in radians
0.785398
normalized alignment
0.707107

Exact expressions use =. Rounded computations use ≈. All arrows use these same quantities.

A positive dot product means an acute angle: the directions partly agree.

u⋅v=uxvx+uyvy=6+(0)=6\begin{aligned}\mathbf u\cdot\mathbf v&=u_xv_x+u_yv_y\\&=6+(0)=6\end{aligned}
cos⁡θ=u⋅v∥u∥∥v∥≈0.707107,θ≈0.785398 rad\cos\theta=\frac{\mathbf u\cdot\mathbf v}{\norm{\mathbf u}\norm{\mathbf v}}\approx 0.707107,\quad\theta\approx 0.785398\,\mathrm{rad}

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

Drag either vector or turn v by π/2. The arc shows the smaller angle, the component products show the arithmetic, and the parallel part shows alignment along u.

Start with the worked pair and predict the sign after a quarter-turn of v\mathbf v. Keep turning until it points against u\mathbf u. Choose Perpendicular, then Zero vector, and compare the two states: both have dot product zero, but only one has a defined right angle.

Intuition: alignment with size

Two equally directed vectors reinforce the same move. Perpendicular vectors share no component along each other’s direction. Opposite vectors disagree. The dot product encodes this with a positive value, zero, or a negative value. It also depends on length: doubling either vector doubles the product, even if the angle stays unchanged.

The parallel arrow in the stage shows the part of v\mathbf v along the line of u\mathbf u. Its signed scalar component is positive on u\mathbf u‘s ray and negative on the opposite ray. Multiplying that scalar component by ∥u∥\norm{\mathbf u} gives the dot product. The complete decomposition is the subject of II.5 Projection.

Definition

For u,v∈R2\mathbf u,\mathbf v\in\mathbb R^2,

u⋅v=uxvx+uyvy.\mathbf u\cdot\mathbf v=u_xv_x+u_yv_y.

The output is a scalar, not a vector. If both vectors are nonzero and θ∈[0,π]\theta\in[0,\pi] is their smaller, unsigned angle,

u⋅v=∥u∥∥v∥cos⁡θ.\mathbf u\cdot\mathbf v=\norm{\mathbf u}\norm{\mathbf v}\cos\theta.

Angles are in radians. The two vectors are orthogonal when their dot product is zero. For nonzero vectors this means perpendicular directions and θ=π/2\theta=\pi/2. The zero vector is algebraically orthogonal to every vector, but it has no direction and forms no defined angle.

Mechanics: products before the sum

The inspector separates uxvxu_xv_x and uyvyu_yv_y. Either product may be negative; their sum determines alignment. In the perpendicular preset u=(3,0)\mathbf u=(3,0) and v=(0,3)\mathbf v=(0,3), both products vanish. For (2,1)(2,1) and (−1,2)(-1,2), they instead cancel as −2+2=0-2+2=0. Perpendicularity does not require axis alignment or a zero component.

For nonzero vectors, a positive product means an angle below π/2\pi/2; a negative product means an angle above π/2\pi/2. At identical directions θ=0\theta=0, and at opposite directions θ=π\theta=\pi. The arc always represents this smaller angle, rather than a directed full rotation. Turning clockwise and counter-clockwise to the same endpoint can therefore give the same angle.

Derivation: components meet geometry

Form the triangle with sides u\mathbf u, v\mathbf v, and the vector between their tips. Expand the squared length of that last side:

∥u−v∥2=∥u∥2+∥v∥2−2(uxvx+uyvy).\norm{\mathbf u-\mathbf v}^2 =\norm{\mathbf u}^2+\norm{\mathbf v}^2 -2(u_xv_x+u_yv_y).

The cosine rule for the same triangle gives

∥u−v∥2=∥u∥2+∥v∥2−2∥u∥∥v∥cos⁡θ.\norm{\mathbf u-\mathbf v}^2 =\norm{\mathbf u}^2+\norm{\mathbf v}^2 -2\norm{\mathbf u}\norm{\mathbf v}\cos\theta.

Equating the final terms proves the geometric identity. Symmetry follows directly from multiplication of real numbers: u⋅v=v⋅u\mathbf u\cdot\mathbf v=\mathbf v\cdot\mathbf u. Distributivity gives u⋅(av+bw)=a(u⋅v)+b(u⋅w)\mathbf u\cdot(a\mathbf v+b\mathbf w)=a(\mathbf u\cdot\mathbf v)+b(\mathbf u\cdot\mathbf w). Finally, v⋅v=∥v∥2\mathbf v\cdot\mathbf v=\norm{\mathbf v}^2.

The geometric identity also implies ∣u⋅v∣≤∥u∥∥v∥|\mathbf u\cdot\mathbf v|\le\norm{\mathbf u}\norm{\mathbf v}, since ∣cos⁡θ∣≤1|\cos\theta|\le1. This bound explains the legal range of a computed cosine.

Worked examples

For u=(3,0)\mathbf u=(3,0) and v=(2,2)\mathbf v=(2,2), the product is 66. Their lengths are 33 and 222\sqrt2, so cos⁡θ=1/2\cos\theta=1/\sqrt2 and θ=π/4\theta=\pi/4. Inspect the arithmetic before the angular interpretation.

Inspect the worked calculation

For u = (3, 0) and v = (2, 2), multiply matching components: 6 + 0 = 6.

u⋅v=uxvx+uyvy=6+(0)=6\begin{aligned}\mathbf u\cdot\mathbf v&=u_xv_x+u_yv_y\\&=6+(0)=6\end{aligned}
first direction
(3, 0)
second vector
(2, 2)
signed component along u
6 / (3)2
dot product
6
first component product
6
second component product
0
angle in radians
0.785398
normalized alignment
0.707107
Step from component products to the cosine relation.

For (2,−1)(2,-1) and (3,4)(3,4), the dot product is 6−4=2>06-4=2>0: the angle is acute even though one matching-component product is negative. For (1,0)(1,0) and (−1,0)(-1,0), the product is −1-1 and the angle is π\pi. These cases separate the sign of one component from the sign of overall alignment.

Executable reference code

The pedagogical dot product interprets decimal components exactly. Its angle routine first normalizes rescaled finite vectors and then checks the cosine range. NumPy’s @@ on two one-dimensional arrays computes their dot product; the remaining lines expose the angle calculation and the zero checks.

code/python/linear_dot.py
from fractions import Fraction
from math import acos, hypot, isfinite, ulp


def dot(u, v):
    if len(u) != 2 or len(v) != 2:
        raise ValueError('Expected two components per vector')
    return sum(Fraction(str(x)) * Fraction(str(y)) for x, y in zip(u, v))


def angle(u, v):
    directions = []
    for w in (u, v):
        if len(w) != 2 or not all(isfinite(x) for x in w):
            raise ValueError('Expected finite two-component vectors')
        m = max(map(abs, w))
        if m == 0:
            raise ValueError('An angle requires two nonzero vectors')
        w = tuple(x / m for x in w)
        h = hypot(*w)
        directions.append(tuple(x / h for x in w))
    cosine = sum(x*y for x, y in zip(*directions))
    if not isfinite(cosine) or abs(cosine) > 1 + 8 * ulp(1.0):
        raise ArithmeticError('Invalid cosine; clipping would hide an error')
    return acos(max(-1.0, min(1.0, cosine)))


if __name__ == '__main__':
    assert dot((2, 1), (-1, 2)) == 0
    assert dot((2, -1), (3, 4)) == 2
code/python/linear_dot_numpy.py
import numpy as np

u = np.array([3.0, 0.0])
v = np.array([2.0, 2.0])
product = u @ v
# Rescale each vector before normalizing, avoiding squared-norm overflow.
if not np.isfinite(u).all() or not np.isfinite(v).all():
    raise ValueError('Finite components required')
mu, mv = np.max(np.abs(u)), np.max(np.abs(v))
if mu == 0 or mv == 0:
    raise ValueError('Angle undefined at zero')
un, vn = u / mu, v / mv
un, vn = un / np.hypot(*un), vn / np.hypot(*vn)
cosine = float(un @ vn)
if not np.isfinite(cosine) or abs(cosine) > 1 + 8 * np.finfo(float).eps:
    raise ArithmeticError('Invalid cosine; do not conceal it with clipping')
angle = np.arccos(np.clip(cosine, -1, 1))
assert product == 6
assert np.isclose(angle, np.pi / 4)

Explore

With u=(2,1)\mathbf u=(2,1), construct a perpendicular vector by solving 2vx+vy=02v_x+v_y=0. Compare (−1,2)(-1,2) and (−2,4)(-2,4): the angle agrees, although their lengths differ. Now scale a nonperpendicular vector by 22: predict the changed dot product and unchanged cosine. Scale by −1-1: the dot product changes sign and the angle becomes π−θ\pi-\theta.

Common mistakes

Multiplying component sums, (ux+uy)(vx+vy)(u_x+u_y)(v_x+v_y), introduces cross terms and is not a dot product. Treating zero product as proof of a right angle overlooks zero vectors. A large positive product also does not necessarily mean a smaller angle than a smaller product: different vector lengths can dominate the comparison. Normalized alignment removes that size dependence.

Numerical considerations

Computing arccos⁡((u⋅v)/(∥u∥∥v∥))\arccos((\mathbf u\cdot\mathbf v)/(\norm{\mathbf u}\norm{\mathbf v})) requires two nonzero vectors and finite, valid arithmetic. Normalizing after rescaling avoids intermediate squared-norm overflow. A rounded cosine can land a few ulps outside [−1,1][-1,1]. The code allows at most eight binary64 epsilon units beyond an endpoint, reflecting the rounding of the normalized products and their sum. Values such as 1.41.4, infinity, or NaN are rejected; unrestricted clipping would hide an invalid computation.

Near parallel directions, arccos⁡\arccos is sensitive because cosine changes very slowly with angle. The stage retains an exact decimal cross product c=uxvy−uyvxc=u_xv_y-u_yv_x and evaluates the equivalent smaller angle atan2⁡(∣c∣,u⋅v)\operatorname{atan2}(|c|,\mathbf u\cdot\mathbf v). This preserves a small angle that might be lost by rounding cosine to 11. Exact decimal orthogonality in the stage uses no tolerance; measured floating-point vectors require a comparison scaled to their magnitudes and measurement uncertainty.

Engineering and ML connections

Work done by a force along a displacement is a dot product: perpendicular force contributes no work along that move. A weighted feature score also multiplies matching coordinates and sums them. Cosine similarity compares normalized alignment, so it is undefined for a zero input unless an application declares a separate convention. Two-dimensional geometry supplies the mental model; the matching-component sum extends to longer vectors.

Exercises

calculation

Multiply matching components

u = (2, −1), v = (3, 4). Give u · v.

calculation

Exact perpendicularity

u = (2, 1), v = (−1, 2). Give their dot product.

construction

Construct a perpendicular move

u = (2, 1). A perpendicular v has vy = 4. Find vx.

prediction

Predict the angle

Two nonzero vectors have a negative dot product. What can you conclude?

Choose one answer

explanation

A clipping policy

A computed cosine is 1.4. Should it be clipped to 1 before acos?

Choose one answer

Summary and checkpoints

A dot product is both a matching-component sum and length-weighted alignment. Check that you can predict its sign, construct perpendicular vectors, distinguish algebraic orthogonality from a right angle at zero, and explain the narrow clipping policy. The next chapter turns the parallel component into a complete projection-and-residual decomposition.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available