Mathematical Foundations

III.8 · Calculus

Which way is uphill — and how steep is every other way?

Place a point on a contour map and aim a direction. The gradient gives the rate in that direction by a dot product, points along steepest increase and stands perpendicular to the level curve.

Measure the rate of change in any direction

Gradient (drawn ×0.25) on the contours of f = 0.5x² + 2y²

Contours of f = 0.5x² + 2y². At (1, 0.5) the gradient is (1, 2), drawn at scale 0.25; the dashed line is tangent to the level curve and perpendicular to it. The blue arrow is the unit direction of d = (1, 0).

Directional derivative versus direction angle θ (radians)

The directional derivative ∇f·u = |∇f| cos(θ − θ∇) peaks at θ∇ ≈ 1.107 with value |∇f| ≈ 2.236068 and is 0 along the level curve.

Point
(1, 0.5)
Gradient (exact)
(1, 2)
Steepest rate of increase
2.236068
Direction vector
(1, 0)
Unnormalised rate (exact)
1
Directional derivative
1
Gradient · level tangent
0

Exact values use =; binary64 approximations use ≈. Undefined values state their reason.

Moving in direction u changes f at rate 1, between −|∇f| and |∇f|. The maximum ≈ 2.236068 occurs along ∇f itself.

∇f(1,0.5)=[12]\nabla f(1,0.5)=\begin{bmatrix}1\\2\end{bmatrix}
∥∇f∥=5≈2.236068\|\nabla f\|=\sqrt{5}\approx 2.236068
Duf=∇f⋅d∥d∥=11=1D_{\mathbf u}f=\nabla f\cdot\frac{\mathbf d}{\|\mathbf d\|}=\frac{1}{1}=1
∇f⋅t=(1)(−2)+(2)(1)=0\nabla f\cdot\mathbf t=(1)(-2)+(2)(1)=0

Compute the gradient

The partial derivatives at the point form ∇f = (1, 2).

∇f(1,0.5)=[12]\nabla f(1,0.5)=\begin{bmatrix}1\\2\end{bmatrix}

from −2.5 to 2.5, up to 2 decimal places

from −2.5 to 2.5, up to 2 decimal places

from −2 to 2, up to 2 decimal places

from −2 to 2, up to 2 decimal places

Drag the point or the blue direction tip. The orange arrow is the gradient at its declared drawing scale; the dashed line is tangent to the level curve; the lower plane shows the rate for every direction angle.

At (1,12)(1,\tfrac12) on the valley x2/2+2y2x^2/2+2y^2, the gradient is (1,2)(1,2). In the direction (1,0)(1,0) the height changes at rate 11. Choose Along the gradient: the rate rises to ∥∇f∥=5≈2.236\|\nabla f\|=\sqrt5\approx2.236, the largest possible. Choose Along the level curve: the rate is exactly 00.

Intuition: one vector answers every direction

Walking from a point in a direction u\mathbf u, the height changes at some rate. You might expect a different calculation for every direction. For a differentiable function there is a single vector — the gradient — and the rate in direction u\mathbf u is just its component along u\mathbf u. The profile plot shows the consequence: as the direction turns, the rate traces a cosine wave.

Definition

The gradient of ff at pp is the vector of partial derivatives,

∇f(p)=[∂f/∂x∂f/∂y].\nabla f(p)=\begin{bmatrix}\partial f/\partial x\\ \partial f/\partial y\end{bmatrix}.

For a unit vector u\mathbf u, the directional derivative is

Duf(p)=lim⁡h→0f(p+hu)−f(p)h.D_{\mathbf u}f(p)=\lim_{h\to0}\frac{f(p+h\mathbf u)-f(p)}{h}.

When ff is differentiable, Duf=∇f⋅uD_{\mathbf u}f=\nabla f\cdot\mathbf u. A nonzero direction vector d\mathbf d is normalised first: u=d/∥d∥\mathbf u=\mathbf d/\|\mathbf d\|. The zero vector has no direction.

Mechanics: what the explorer computes

The gradient is exact at rational points. The unnormalised product ∇f⋅d\nabla f\cdot\mathbf d is exact; dividing by ∥d∥\|\mathbf d\| is exact when ∥d∥2\|\mathbf d\|^2 is the square of a rational and is otherwise shown with ≈\approx. The gradient arrow is drawn at the scale stated in the title, so its direction is faithful and its length is proportional. The level-curve tangent is perpendicular to the gradient, and the inspector checks ∇f⋅t=0\nabla f\cdot\mathbf t=0 exactly.

Derivation: why the dot product appears

Differentiability means f(p+δ)=f(p)+∇f⋅δ+o(∥δ∥)f(p+\boldsymbol\delta)=f(p)+\nabla f\cdot\boldsymbol\delta+o(\|\boldsymbol\delta\|). Put δ=hu\boldsymbol\delta=h\mathbf u and divide by hh:

f(p+hu)−f(p)h=∇f⋅u+o(1).\frac{f(p+h\mathbf u)-f(p)}{h}=\nabla f\cdot\mathbf u+o(1).

Letting h→0h\to0 gives Duf=∇f⋅u=∥∇f∥cos⁡θD_{\mathbf u}f=\nabla f\cdot\mathbf u=\|\nabla f\|\cos\theta, where θ\theta is the angle between u\mathbf u and ∇f\nabla f. The rate is largest when θ=0\theta=0 (steepest ascent, value ∥∇f∥\|\nabla f\|), smallest when θ=π\theta=\pi, and zero when u⊥∇f\mathbf u\perp\nabla f. Along a level curve ff is constant, so its tangent direction has zero rate: the gradient is perpendicular to regular level curves.

Worked example

For f=x2/2+2y2f=x^2/2+2y^2 at (1,12)(1,\tfrac12): ∇f=(x,4y)=(1,2)\nabla f=(x,4y)=(1,2). With d=(3,4)\mathbf d=(3,4), ∥d∥=5\|\mathbf d\|=5, so

Duf=(1,2)⋅(3,4)5=115.D_{\mathbf u}f=\frac{(1,2)\cdot(3,4)}{5}=\frac{11}{5}.

The steepest rate is 1+4=5\sqrt{1+4}=\sqrt5, and the tangent to the level curve is t=(−2,1)\mathbf t=(-2,1), for which ∇f⋅t=0\nabla f\cdot\mathbf t=0.

Replay the worked derivation

Compute the gradient

The partial derivatives at the point form ∇f = (1, 2).

∇f(1,0.5)=[12]\nabla f(1,0.5)=\begin{bmatrix}1\\2\end{bmatrix}
Replay: gradient, normalisation, projection and perpendicularity.

Stationary points and undefined cases

Where ∇f=0\nabla f=\mathbf 0 (the Stationary point preset), every directional derivative is 00 and there is no direction of steepest ascent; the stage draws no gradient arrow rather than an arbitrary one. A zero direction vector cannot be normalised, so the directional derivative is reported as undefined. At points where ff is not differentiable, the formula ∇f⋅u\nabla f\cdot\mathbf u is not guaranteed even when the partials exist; the surfaces here are polynomials, which are differentiable everywhere.

Executable reference code

The reference computes exact gradients and directional derivatives with Fraction, and confirms DufD_{\mathbf u}f against the limit definition along rational unit directions such as (3/5,4/5)(3/5,4/5). The NumPy version maximises the directional derivative over many angles and finds the gradient direction.

code/python/calculus_gradient.py
"""Gradient and directional derivatives, exact; the limit definition agrees with grad . u (III.8)."""
from fractions import Fraction as F

f = lambda x, y: x * x / 2 + 2 * y * y
grad = lambda x, y: (x, 4 * y)

p = (F(1), F(1, 2))
g = grad(*p)
assert g == (1, 2)


def directional(d):
    if d == (0, 0):
        raise ValueError("the zero vector has no direction")
    n2 = d[0] ** 2 + d[1] ** 2
    return (g[0] * d[0] + g[1] * d[1]), n2           # rate = numerator / sqrt(n2)


num, n2 = directional((F(3), F(4)))
assert (num, n2) == (11, 25)                          # rate 11/5

# Limit definition along the unit direction u = (3/5, 4/5): m(h) is a polynomial of degree 1 in h.
u = (F(3, 5), F(4, 5))
m = lambda h: (f(p[0] + h * u[0], p[1] + h * u[1]) - f(*p)) / h
assert 2 * m(F(1, 4)) - m(F(1, 2)) == F(11, 5)

# The gradient is perpendicular to the level-curve tangent t = (-g_y, g_x).
t = (-g[1], g[0])
assert g[0] * t[0] + g[1] * t[1] == 0
code/python/calculus_gradient_numpy.py
"""The steepest direction maximises grad . u over all unit vectors (III.8)."""
import numpy as np

g = np.array([1.0, 2.0])
theta = np.linspace(-np.pi, np.pi, 3601)
U = np.stack([np.cos(theta), np.sin(theta)], axis=1)
rates = U @ g
best = U[np.argmax(rates)]
assert abs(rates.max() - np.linalg.norm(g)) < 1e-6
assert np.allclose(best, g / np.linalg.norm(g), atol=1e-3)
assert abs(rates.min() + np.linalg.norm(g)) < 1e-6

Explore

On Saddle, find two directions with rate zero: they are the two arms of the level curve through the point. On Tilted plane, the gradient is the same everywhere and the contours are parallel lines perpendicular to it. Shorten d\mathbf d without changing its direction: the directional derivative does not change, because d\mathbf d is normalised.

Common mistakes

Using an unnormalised direction, which scales the “rate” by ∥d∥\|\mathbf d\|. Drawing the gradient tangent to the contour instead of perpendicular to it. Assuming the gradient points toward a minimum: it points toward the steepest increase; the steepest decrease is −∇f-\nabla f.

Numerical considerations

Normalising a tiny direction vector divides by a tiny number and amplifies rounding; the zero vector must be rejected explicitly, not left to produce NaN. When ∇f\nabla f is nearly zero its direction is numerically unreliable even if its components are accurate: steepest-ascent directions near stationary points are ill-conditioned.

Engineering and ML connections

Gradient descent (VI.4) steps along −∇f-\nabla f because it is locally the steepest decrease. Directional derivatives appear in line searches and in Jacobian–vector products, which automatic differentiation (III.10) computes without forming the whole gradient. Level-set geometry also underlies constraints in optimisation (VI.9).

Exercises

calculation

Compute a gradient

f(x, y) = x²/2 + 2y². Give ∇f at (1, 0.5).

calculation

A directional derivative

With ∇f = (1, 2), find D_u f for u = (3/5, 4/5).

calculation

Steepest rate

With ∇f = (3, 4), what is the largest directional derivative?

prediction

Gradient and level curves

Why is ∇f perpendicular to the level curve through a regular point?

Choose one answer

prediction

Zero vectors

d = (0, 0). What is the directional derivative “in direction d”?

Choose one answer

Summary and checkpoints

The gradient collects the partial derivatives; for a unit direction u\mathbf u, Duf=∇f⋅uD_{\mathbf u}f=\nabla f\cdot\mathbf u. It points along steepest increase with rate ∥∇f∥\|\nabla f\| and is perpendicular to regular level curves. At stationary points it vanishes, and zero directions have no rate. Next, III.9 differentiates maps with several outputs: the Jacobian.

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