Mathematical Foundations

II.5 · Linear Algebra

Which part of a move follows a direction?

Split one vector into a parallel move and a perpendicular residual. The projection reconstructs the parallel part; the residual measures distance to the line.

Split a vector along a direction

The arrow along u plus the perpendicular residual reconstructs v exactly. The distance to the entire line is ‖r‖; the signed scalar component may be negative.

first direction
(2, 1)
second vector
(1, 3)
alignment numerator
5
squared direction length
5
coefficient multiplying u
1
signed scalar projection
5 / (√5)2.236068…
vector projection
(2, 1)
perpendicular residual
(−1, 2)
orthogonality check
0
distance to the line
√52.236068…

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

The arrow along u plus the perpendicular residual reconstructs v exactly. The distance to the entire line is ‖r‖; the signed scalar component may be negative.

α=55=1,proj⁡uv=[21]\alpha=\frac{5}{5}=1,\quad\operatorname{proj}_{\mathbf u}\mathbf v=\begin{bmatrix}2\\1\end{bmatrix}
v=[21]+[−12],r⋅u=0\mathbf v=\begin{bmatrix}2\\1\end{bmatrix}+\begin{bmatrix}-1\\2\end{bmatrix},\quad\mathbf r\cdot\mathbf u=0

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

Move the direction u or the vector v. The projection lies along u; the residual runs from the projection tip to v's tip. Their sum reconstructs v, and the residual dot u is exactly zero.

Try Negative component and observe that the projection can lie on the ray opposite u\mathbf u. Try Perpendicular: the projection becomes zero and the residual is the entire vector. Finally try Zero direction and identify why the formula cannot choose a line.

Intuition: a shadow on a line

Imagine dropping a perpendicular from v\mathbf v‘s tip onto the line through the origin in direction u\mathbf u. The point where it lands is the tip of the projection vector. The move from that point to v\mathbf v‘s tip is the residual. This splits one move into “along the line” and “away from the line.”

The direction vector determines a whole line, not only the ray in which its arrow points. Consequently a projection may have a negative coefficient. Replacing u\mathbf u by another nonzero multiple leaves the line and the vector projection unchanged. An oriented scalar component can change sign when the direction reverses.

Definition

For a nonzero direction u\mathbf u,

α=v⋅uu⋅u,proj⁡uv=αu,r=v−proj⁡uv.\alpha=\frac{\mathbf v\cdot\mathbf u}{\mathbf u\cdot\mathbf u},\qquad \operatorname{proj}_{\mathbf u}\mathbf v=\alpha\mathbf u,\qquad \mathbf r=\mathbf v-\operatorname{proj}_{\mathbf u}\mathbf v.

The signed scalar projection is

s=v⋅u∥u∥,proj⁡uv=su^.s=\frac{\mathbf v\cdot\mathbf u}{\norm{\mathbf u}},\qquad \operatorname{proj}_{\mathbf u}\mathbf v=s\widehat{\mathbf u}.

These quantities have different meanings. α\alpha is the weight on the chosen vector u\mathbf u. The scalar ss is signed distance along its unit direction. The vector projection has two components. The distance from v\mathbf v‘s tip to the entire line is the nonnegative number ∥r∥\norm{\mathbf r}.

Mechanics: two checks on one decomposition

The inspector exposes the numerator, denominator, coefficient, projected vector, residual, and distance. A first check is reconstruction: projected vector plus residual equals v\mathbf v. A second check is perpendicularity: r⋅u=0\mathbf r\cdot\mathbf u=0. Reconstruction alone is insufficient, because infinitely many arbitrary pairs add to v\mathbf v; perpendicularity identifies the orthogonal decomposition.

The original v\mathbf v may be zero. If u\mathbf u is nonzero, its projection and residual are then both zero, and the distance is zero. The forbidden case is zero direction, not zero data. The stage shows all direction-dependent quantities as undefined in that case.

Derivation: force the residual to be orthogonal

Any vector parallel to u\mathbf u can be written αu\alpha\mathbf u. Choose α\alpha by requiring the remainder to be orthogonal:

0=(v−αu)⋅u=v⋅u−α(u⋅u).0=(\mathbf v-\alpha\mathbf u)\cdot\mathbf u =\mathbf v\cdot\mathbf u-\alpha(\mathbf u\cdot\mathbf u).

Because u≠0\mathbf u\ne0, its squared norm is positive, so division gives the stated coefficient. Substitution proves residual orthogonality exactly. The coefficient is unique, hence so are the parallel vector and residual.

Why does this yield the closest point on the line? For any other line point tut\mathbf u,

∥v−tu∥2=∥r+(α−t)u∥2=∥r∥2+(α−t)2∥u∥2.\norm{\mathbf v-t\mathbf u}^2 =\norm{\mathbf r+(\alpha-t)\mathbf u}^2 =\norm{\mathbf r}^2+(\alpha-t)^2\norm{\mathbf u}^2.

The cross term vanishes by orthogonality. The second term is nonnegative and becomes zero exactly at t=αt=\alpha. Thus the projection minimizes distance to the line, and its residual length is that minimum. This is a geometric derivation, without needing a calculus optimizer.

Worked examples

For u=(2,1)\mathbf u=(2,1) and v=(1,3)\mathbf v=(1,3), the numerator and denominator are both 55, so α=1\alpha=1. Projection (2,1)(2,1) plus residual (−1,2)(-1,2) equals (1,3)(1,3). The check is (−1,2)⋅(2,1)=−2+2=0(-1,2)\cdot(2,1)=-2+2=0. The distance is 5\sqrt5, while the signed scalar projection is 5/5=55/\sqrt5=\sqrt5; these happen to agree in this example but are different quantities.

Inspect the worked calculation

For u = (2, 1) and v = (1, 3), v · u = 5 and u · u = 5; the multiplier is 1.

α=55=1,proj⁡uv=[21]\alpha=\frac{5}{5}=1,\quad\operatorname{proj}_{\mathbf u}\mathbf v=\begin{bmatrix}2\\1\end{bmatrix}
first direction
(2, 1)
second vector
(1, 3)
alignment numerator
5
squared direction length
5
coefficient multiplying u
1
signed scalar projection
5 / (√5)2.236068…
vector projection
(2, 1)
perpendicular residual
(−1, 2)
orthogonality check
0
distance to the line
√52.236068…
Inspect the coefficient, then the reconstruction and orthogonality check.

For u=(1,0)\mathbf u=(1,0) and v=(−3,2)\mathbf v=(-3,2), projection is (−3,0)(-3,0), signed scalar projection is −3-3, and distance is 22. This example makes their distinctions visible: a negative along-line component does not imply negative distance.

Executable reference code

The pedagogical version computes the coefficient and vectors exactly from decimal inputs and asserts residual orthogonality. The NumPy example uses a rescaled unit direction, which avoids forming a very large u⋅u\mathbf u\cdot\mathbf u. Numerical reconstruction and orthogonality require tolerances appropriate to the data scale.

code/python/linear_projection.py
from fractions import Fraction
from math import hypot


def project(v, u):
    if len(u) != 2 or len(v) != 2:
        raise ValueError('Expected two components per vector')
    u, v = (tuple(Fraction(str(x)) for x in w) for w in (u, v))
    denominator = sum(x*x for x in u)
    if denominator == 0:
        raise ValueError('Projection direction must be nonzero')
    product = sum(x*y for x, y in zip(v, u))
    factor = product / denominator
    projection = tuple(factor*x for x in u)
    residual = tuple(y-x for y, x in zip(v, projection))
    assert sum(x*y for x, y in zip(residual, u)) == 0
    return projection, residual, hypot(*residual)


if __name__ == '__main__':
    p, r, distance = project((1, 3), (2, 1))
    assert p == (2, 1) and r == (-1, 2)
    assert distance == hypot(-1, 2)
code/python/linear_projection_numpy.py
import numpy as np

v = np.array([1.0, 3.0])
u = np.array([2.0, 1.0])
if not np.isfinite(u).all() or not np.isfinite(v).all():
    raise ValueError('Finite components required')
m = np.max(np.abs(u))
if m == 0:
    raise ValueError('Projection direction is zero')
un = u / m
un = un / np.hypot(*un)
signed_scalar = v @ un
projected = signed_scalar * un
residual = v - projected
distance = np.hypot(*residual)
assert np.allclose(projected, [2, 1])
assert np.allclose(residual, [-1, 2])
assert np.isclose(residual @ un, 0, atol=1e-15)
# Rescaling u protects its norm, not arbitrary overflow in v @ un.

Explore

Hold v=(1,3)\mathbf v=(1,3) fixed and compare u=(2,1)\mathbf u=(2,1) with (4,2)(4,2) and (−2,−1)(-2,-1). Predict which of α\alpha, ss, and the projected vector changes. Now make v\mathbf v parallel to u\mathbf u and explain why the residual vanishes. Make them perpendicular and explain why the coefficient vanishes instead. A projection onto a vertical direction works without a slope calculation or division by the horizontal component.

Common mistakes

Dividing by ∥u∥\norm{\mathbf u} and then multiplying by u\mathbf u mixes scalar and vector projection formulas. The vector formula requires squared length in its denominator unless u\mathbf u is already unit length. Another mistake measures distance to a ray or finite segment while using a formula for an entire line; those constrained problems require checking endpoints or allowed parameters.

Numerical considerations

The bounded stage uses exact fractions for the coefficient and residual, so its orthogonality check is an exact zero rather than a rounded display coincidence. Direct floating-point division by a squared norm can fail when that square overflows or underflows. Normalizing after rescaling protects the direction calculation. It does not guarantee that every later dot product or residual is representable: enormous data can overflow the signed component, and subtracting nearly equal components can lose relative accuracy in a tiny residual. A small residual may be meaningful only to the precision of the input measurements. The displayed distance is an exact radical where supported, followed by a clearly marked approximation.

Engineering and ML connections

Projection separates velocity along a track from sideways motion. It also measures the part of data explained by one direction and the part left over. This prepares the geometric view of least squares in later linear algebra: choose an approximation in a span and study the orthogonal residual. The current chapter projects onto one line; it does not yet solve a general fitting system.

Exercises

calculation

Project onto a direction

u = (2, 1), v = (1, 3). Give projᵤv.

calculation

Find what is left over

For u = (2, 1), v = (1, 3), find the residual v − projᵤv.

construction

Construct a pure residual

A vector v = (x, 2) projects to zero along u = (2, 1). Find x.

prediction

A negative scalar component

The signed scalar projection is negative. What is the distance to the line?

Choose one answer

explanation

Change the direction vector

Replace a nonzero u by −3u. Does the vector projection change?

Choose one answer

Summary and checkpoints

A nonzero direction determines a unique orthogonal split of every vector. Verify reconstruction and residual orthogonality, distinguish α\alpha from ss and the vector projection, and explain the nearest-line proof. II.6 Span asks what two weighted directions can reach.

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