Mathematical Foundations

II.3 · Linear Algebra

How do you keep direction and remove length?

A norm turns a vector into a nonnegative size. Divide a nonzero vector by its Euclidean norm to retain only its direction, and compare how three norms define different unit balls.

Length, unit direction, and three unit balls

The normalized arrow has length 1 and keeps the direction of v. Diamond = L₁ unit ball; circle = L₂; square = L∞. These are three different meanings of distance.

original vector
(3, 4)
Euclidean length
5
taxicab length
7
largest component magnitude
4
unit vector (exact expression)
(3 / (5), 4 / (5))
unit x-component
3 / (5)0.600000
unit y-component
4 / (5)0.800000
unit length
1

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

The normalized arrow has length 1 and keeps the direction of v. Diamond = L₁ unit ball; circle = L₂; square = L∞. These are three different meanings of distance.

∥v∥2=25=5\norm{\mathbf v}_2=\sqrt{25}=5
v^=15[34],∥v^∥=1\widehat{\mathbf v}=\frac{1}{5}\begin{bmatrix}3\\4\end{bmatrix},\quad \norm{\widehat{\mathbf v}}=1
∥v∥1=7,∥v∥∞=4\norm{\mathbf v}_1=7,\quad\norm{\mathbf v}_\infty=4

from −4 to 4, up to 2 decimal places

from −4 to 4, up to 2 decimal places

Move v. Its normalized arrow ends on the Euclidean unit circle. The diamond is the L₁ unit ball and the square is the L∞ unit ball; these fixed shapes let you compare the definitions.

Try (3,4)(3,4), then (1,1)(1,1), then zero. Predict which quantities remain defined at zero. The three length measures all become zero, while the unit-vector rows disappear into an explicit exception. Moving the tip away from zero restores a unit direction.

Intuition: size depends on what you measure

Euclidean length measures a straight move. Taxicab length counts the total travel along the two coordinate axes. The largest-component norm measures the worst coordinate displacement. These answer different questions about the same vector. None depends on which quadrant contains it, because signs describe direction rather than size.

Normalization removes Euclidean length without changing a nonzero vector’s direction. A short vector and a long vector along the same ray give the same normalized arrow. A vector on the opposite ray gives the negative unit vector. The unit circle acts as a catalogue of possible directions.

Definition

For v=(vx,vy)\mathbf v=(v_x,v_y),

∥v∥2=vx2+vy2,∥v∥1=∣vx∣+∣vy∣,∥v∥∞=max⁡(∣vx∣,∣vy∣).\norm{\mathbf v}_2=\sqrt{v_x^2+v_y^2},\qquad \norm{\mathbf v}_1=|v_x|+|v_y|,\qquad \norm{\mathbf v}_\infty=\max(|v_x|,|v_y|).

An unqualified norm in this block means the Euclidean norm. A unit vector has Euclidean norm 11. The normalized vector is defined only for v≠0\mathbf v\ne\mathbf0:

v^=v∥v∥2.\widehat{\mathbf v}=\frac{\mathbf v}{\norm{\mathbf v}_2}.

A norm is nonnegative, vanishes only at zero, scales by the absolute value of a scalar, and satisfies the triangle inequality ∥u+v∥≤∥u∥+∥v∥\norm{\mathbf u+\mathbf v}\le\norm{\mathbf u}+\norm{\mathbf v}. For Euclidean distance, the straight route is no longer than the route through an intermediate point. Equality occurs for moves along the same ray, including a zero move.

Mechanics: the three unit balls

The unit ball of a norm consists of vectors whose norm is at most 11. The stage draws its boundary. For L1L_1, ∣x∣+∣y∣=1|x|+|y|=1 gives the diamond. For L∞L_\infty, max⁡(∣x∣,∣y∣)=1\max(|x|,|y|)=1 gives the square. For L2L_2, x2+y2=1x^2+y^2=1 gives the circle. These shapes follow directly from the norm definitions, rather than from the current vector’s length.

At (1,1)(1,1) the norms are 22, 2\sqrt2, and 11, respectively. The point lies on the square boundary, outside the Euclidean circle, and outside the diamond. If you divide by L1L_1 instead, the resulting vector lands on the diamond; it generally is not a Euclidean unit vector.

Derivation: why the normalized length is one

The length is positive when the vector is nonzero. Apply the scaling law from II.2 Scalar multiplication:

∥v^∥2=∣1∥v∥2∣∥v∥2=1.\norm{\widehat{\mathbf v}}_2 =\left|\frac1{\norm{\mathbf v}_2}\right|\norm{\mathbf v}_2=1.

The scaling factor is positive, so the direction is preserved. At zero the factor would be 1/01/0, and this derivation cannot begin. A zero result is not a substitute: its norm is 00, not 11.

The component inequalities also compare the three norms:

∥v∥∞≤∥v∥2≤∥v∥1.\norm{\mathbf v}_\infty\le\norm{\mathbf v}_2\le\norm{\mathbf v}_1.

The first follows because the sum of squares contains the square of the larger component. For the second, (∣x∣+∣y∣)2=x2+y2+2∣xy∣≥x2+y2(|x|+|y|)^2=x^2+y^2+2|xy|\ge x^2+y^2; taking nonnegative square roots preserves the inequality. Both become equalities on an axis. The ordering does not make one norm universally better; each defines a different size measure.

Worked examples

For (3,4)(3,4) the Euclidean length is 55. Normalization gives (3/5,4/5)(3/5,4/5), whose squared length is 9/25+16/25=19/25+16/25=1. The other norms are 77 and 44.

Inspect the worked calculation

For v = (3, 4), the squared length is 9 + 16 = 25, so the length is 5.

∥v∥2=25=5\norm{\mathbf v}_2=\sqrt{25}=5
original vector
(3, 4)
Euclidean length
5
taxicab length
7
largest component magnitude
4
unit vector (exact expression)
(3 / (5), 4 / (5))
unit x-component
3 / (5)0.600000
unit y-component
4 / (5)0.800000
unit length
1
Inspect the length first, then the normalization and the comparison of norms.

For (1,1)(1,1) the normalized vector is (1/2,1/2)(1/\sqrt2,1/\sqrt2). Those expressions are exact. Decimal components such as 0.7071070.707107 are approximations; squaring rounded display values is not an exact proof of unit length. The inspector separates exact component expressions from their numerical approximations.

Executable reference code

The code distinguishes computing a norm from computing a unit direction. The latter rescales first. The NumPy version checks both shape and finiteness, rejects zero, and uses the same bounded rescaling idea.

code/python/linear_norms.py
from math import hypot, isfinite


def norms(v):
    if len(v) != 2 or not all(isfinite(x) for x in v):
        raise ValueError('Expected two finite components')
    x, y = v
    return hypot(x, y), abs(x) + abs(y), max(abs(x), abs(y))


def normalize(v):
    _, _, m = norms(v)
    if m == 0:
        raise ValueError('Zero has no unit direction')
    x, y = v[0] / m, v[1] / m
    h = hypot(x, y)
    return x / h, y / h


if __name__ == '__main__':
    assert norms((-3, 4)) == (5, 7, 4)
    assert normalize((3, 4)) == (0.6, 0.8)
    assert hypot(*normalize((1.7e308, 1.7e308))) > 0.999999999999999
code/python/linear_norms_numpy.py
import numpy as np


def normalize(v):
    v = np.asarray(v, dtype=float)
    if v.shape != (2,) or not np.isfinite(v).all():
        raise ValueError('Expected a finite two-component vector')
    m = np.max(np.abs(v))
    if m == 0:
        raise ValueError('Zero has no unit direction')
    scaled = v / m
    return scaled / np.hypot(*scaled)


v = np.array([-3.0, 4.0])
l2 = np.hypot(*v)  # avoids squaring overflow; a truly huge norm can still overflow
l1 = np.sum(np.abs(v))
linf = np.max(np.abs(v))
assert (l2, l1, linf) == (5, 7, 4)
assert np.allclose(normalize(v), [-0.6, 0.8])

Explore

Compare (3,4)(3,4) with (1.5,2)(1.5,2): predict the unchanged normalized vector. Reverse both signs and predict the new unit vector. On the horizontal axis, compare all three norms. Move along the diagonal and explain why the three readouts differ even though there is only one arrow. Try zero last, and identify which definition fails.

Common mistakes

Dividing by the squared norm is generally wrong: (3,4)/25(3,4)/25 has length 1/51/5. Dividing each component by its own magnitude gives a sign pattern, not a unit direction. Adding a tiny constant to the denominator can avoid a software exception but changes the formula and produces lengths below 11; such regularization needs its own explicit purpose and definition.

Numerical considerations

Squaring first can overflow or underflow even when a meaningful unit direction exists. For finite v≠0\mathbf v\ne0, set m=max⁡(∣vx∣,∣vy∣)m=\max(|v_x|,|v_y|) and z=v/m\mathbf z=\mathbf v/m. At least one scaled component has magnitude 11, and neither exceeds 11. Then normalize z\mathbf z by its bounded length. This works for enormous inputs and for a pair of smallest subnormal components. The real norm itself may exceed the largest finite binary64 value; direction can still be representable.

Engineering and ML connections

Unit directions separate where a motion goes from how far it travels. Different norms measure different costs: total coordinate movement, Euclidean displacement, or a worst coordinate limit. Feature normalization can reduce the influence of overall scale in a similarity calculation, but discarding magnitude also discards information. Choose it because the task needs direction, rather than because every vector should have unit length.

Exercises

calculation

Three distance measures

For v = (−3, 4), give L₂, L₁ and L∞.

calculation

Normalize the move

Give the unit vector in the direction of v = (−3, 4). Fractions are accepted.

construction

Construct a unit direction

A unit vector has x = 3/5 and points into the first quadrant. Find y.

prediction

Predict normalization at zero

What should normalize((0, 0)) do?

Choose one answer

explanation

Normalize an enormous vector

v = (1.7e308, 1.7e308) has finite components but its length overflows binary64. Which approach still recovers its unit direction?

Choose one answer

Summary and checkpoints

A norm defines size, and Euclidean normalization retains the direction of a nonzero vector with unit length. Check that you can explain the three unit-ball shapes, derive the unit-length property, reject zero, and rescale before dangerous arithmetic. II.4 Dot product compares two directions with a dot product.

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