Mathematical Foundations

III.6 · Calculus

How does a change travel through nested functions?

Nudge the input of a two-stage pipeline and follow the change through the intermediate value to the output. Each stage multiplies it by its own local slope.

Propagate a change through nested functions

Inner function u = g(x)
Outer function y = f(u)

Inner: u = 0.5x² − 1

u = 0.5x² − 1; at x = 2, u = 1 and the local factor du/dx = 2. A step Δx = 0.5 changes u by 1.125.

Outer: y = 0.25u³

y = 0.25u³; at u = 1, y = 0.25 and dy/du = 0.75. The change Δu produces Δy = 2.14892578125.

Composite: y = f(g(x))

Composite y = f(g(x)); its tangent slope at x = 2 is the product 0.75 × 2 = 1.5.

Input
2
Intermediate value g(x)
1
Output f(u)
0.25
Inner sensitivity du/dx
2
Outer sensitivity dy/du, at u
0.75
Chain-rule product dy/dx
1.5
Derivative of the composed formula
1.5
Exact agreement
yes, exactly equal
Actual output change
2.14892578125
Linearized output change
0.75

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

Sensitivities multiply: dy/dx = f′(u)·g′(x), here 0.75 × 2 = 1.5 exactly. The outer slope is evaluated at u = g(x), not at x.

x=2 →  g   u=1 →  f   y=0.25x=2\ \xrightarrow{\;g\;}\ u=1\ \xrightarrow{\;f\;}\ y=0.25
dydx=f′(u)⏟0.75⋅g′(x)⏟2=1.5\frac{dy}{dx}=\underbrace{f'(u)}_{0.75}\cdot\underbrace{g'(x)}_{2}=1.5
Δu=1.125 (linear: 1)\Delta u=1.125\ (\text{linear: }1)
Δy=2.14892578125 (linear: 0.75)\Delta y=2.14892578125\ (\text{linear: }0.75)
h′(2)=1.5(composed, then differentiated)h'(2)=1.5\quad\text{(composed, then differentiated)}

Forward: inner stage

u = g(2) = 1.

u=g(2)=1u=g(2)=1

from −2.5 to 2.5, up to 2 decimal places

from −1.5 to 1.5, up to 2 decimal places

Drag the input x on the inner graph or choose other inner and outer functions. Blue: the change Δu; green: the resulting change Δy; orange: the composite tangent with slope f′(u)·g′(x).

At x=2x=2 the inner function u=x2/2−1u=x^2/2-1 gives u=1u=1, and its tangent slope is 22: a small change in xx is doubled. The outer function y=u3/4y=u^3/4 has slope 3/43/4 at u=1u=1. The composite slope is 34⋅2=32\tfrac34\cdot2=\tfrac32, and the inspector confirms it exactly by differentiating the composed polynomial. Now choose Inner slope 0: whatever the outer function does, a flat inner stage stops the change.

Intuition: sensitivities multiply

In a pipeline x→u=g(x)→y=f(u)x\to u=g(x)\to y=f(u), a small change Δx\Delta x becomes Δu≈g′(x)Δx\Delta u\approx g'(x)\Delta x, and that becomes Δy≈f′(u)Δu\Delta y\approx f'(u)\Delta u. Combining,

Δy≈f′(u) g′(x) Δx.\Delta y\approx f'(u)\,g'(x)\,\Delta x .

Each stage contributes its local amplification factor, and factors multiply — just as two gearboxes in a row multiply their ratios.

Definition

If gg is differentiable at xx and ff is differentiable at u=g(x)u=g(x), then h=f∘gh=f\circ g is differentiable at xx and

h′(x)=f′(g(x)) g′(x),h'(x)=f'(g(x))\,g'(x), dydx=dydu dudx.\frac{dy}{dx}=\frac{dy}{du}\,\frac{du}{dx}.

The outer derivative is evaluated at the intermediate value u=g(x)u=g(x), not at xx.

Mechanics: what the explorer computes

The three planes share one state. The inner plane shows gg, its tangent at xx and the actual change Δu\Delta u; the outer plane shows ff, its tangent at uu and the actual change Δy\Delta y; the composite plane shows f(g(x))f(g(x)) and its tangent with the chain-rule slope. When both stages are polynomials, the inspector also composes them exactly and differentiates the result — an independent route that must agree exactly. For sin⁡\sin and eue^u, values are binary64 and marked ≈\approx.

Derivation

Write the outer function’s local model at uu as

f(u+k)=f(u)+f′(u) k+ε(k) k,f(u+k)=f(u)+f'(u)\,k+\varepsilon(k)\,k,

where ε(k)→0\varepsilon(k)\to0 as k→0k\to0 (this is differentiability of ff). Put k=Δu=g(x+Δx)−g(x)k=\Delta u=g(x+\Delta x)-g(x) and divide by Δx\Delta x:

ΔyΔx=(f′(u)+ε(Δu))⋅ΔuΔx.\begin{aligned}\frac{\Delta y}{\Delta x}&=\big(f'(u)+\varepsilon(\Delta u)\big)\\ &\quad\cdot\frac{\Delta u}{\Delta x}.\end{aligned}

As Δx→0\Delta x\to0, Δu→0\Delta u\to0 (because gg is continuous), so ε(Δu)→0\varepsilon(\Delta u)\to0 and Δu/Δx→g′(x)\Delta u/\Delta x\to g'(x). Hence h′(x)=f′(u)g′(x)h'(x)=f'(u)g'(x). This form avoids dividing by Δu\Delta u, which could be zero.

Worked example

Take g(x)=x2/2−1g(x)=x^2/2-1, f(u)=u3/4f(u)=u^3/4, x=2x=2:

  • forward: u=g(2)=1u=g(2)=1, y=f(1)=1/4y=f(1)=1/4;
  • local factors: g′(2)=2g'(2)=2, f′(1)=3/4f'(1)=3/4;
  • backward product: dy/dx=34⋅2=32dy/dx=\tfrac34\cdot2=\tfrac32.

Composed directly, h(x)=14(x2/2−1)3h(x)=\tfrac14(x^2/2-1)^3 and h′(x)=34(x2/2−1)2⋅xh'(x)=\tfrac34(x^2/2-1)^2\cdot x, which is 32\tfrac32 at x=2x=2. For Δx=1/2\Delta x=1/2 the linearized change is 3/43/4, while the actual change is f(g(2.5))−f(1)=2.149…f(g(2.5))-f(1)=2.149\ldots: the chain rule is exact for rates, approximate for finite steps.

Replay the worked derivation

Forward: inner stage

u = g(2) = 1.

u=g(2)=1u=g(2)=1
Replay the forward pass, the local factors and the backward product.

Toward computational graphs

The replay ends by multiplying backward: start with dy/dy=1dy/dy=1, multiply by f′(u)f'(u), then by g′(x)g'(x). In a longer chain x→u1→u2→⋯→yx\to u_1\to u_2\to\cdots\to y, the same backward product needs one multiplication per stage. When an input feeds several paths, the contributions of the paths add. Chapter III.10 turns this into an algorithm on a graph of elementary operations — reverse-mode automatic differentiation — the computation behind backpropagation. No neural network is needed to understand it.

Executable reference code

The reference composes polynomials exactly with Fraction and checks f′(g(x))g′(x)f'(g(x))g'(x) against the derivative of the composition. The NumPy version evaluates esin⁡xe^{\sin x} on a grid and compares the chain-rule derivative with a centered difference whose error is bounded.

code/python/calculus_chain.py
"""Chain rule on exact polynomials: f'(g(x)) * g'(x) equals the derivative of the composition (III.6)."""
from fractions import Fraction as F


def ev(c, x):
    return sum(ck * x**k for k, ck in enumerate(c))


def der(c):
    return [k * ck for k, ck in enumerate(c)][1:]


def compose(f, g):
    out = [F(0)]
    for ck in reversed(f):                  # Horner: out = out * g + ck
        prod = [F(0)] * (len(out) + len(g) - 1)
        for i, a in enumerate(out):
            for j, b in enumerate(g):
                prod[i + j] += a * b
        prod[0] += ck
        out = prod
    return out


g = [F(-1), F(0), F(1, 2)]        # x**2/2 - 1
f = [F(0), F(0), F(0), F(1, 4)]   # u**3/4
x = F(2)
u = ev(g, x)
chain = ev(der(f), u) * ev(der(g), x)
assert (u, ev(der(g), x), ev(der(f), u), chain) == (1, 2, F(3, 4), F(3, 2))
assert ev(der(compose(f, g)), x) == chain
code/python/calculus_chain_numpy.py
"""e**sin(x): chain-rule derivative versus a centered difference with a bounded error (III.6)."""
import numpy as np

x = np.linspace(-3, 3, 61)
chain = np.exp(np.sin(x)) * np.cos(x)            # f'(u) at u = sin x, times g'(x)
h = 1e-5
centered = (np.exp(np.sin(x + h)) - np.exp(np.sin(x - h))) / (2 * h)
# Truncation ~ h**2 |h'''|/6 (|h'''| < 20 here) plus rounding ~ eps*e/h.
assert np.max(np.abs(chain - centered)) < 20 * h**2 / 6 + 4 * np.finfo(float).eps * np.e / h

Explore

Swap the inner and outer roles: sin⁡(2x−1)\sin(2x-1) versus 2sin⁡x−12\sin x-1 are different functions with different derivatives. Find an xx where the outer slope is zero but the inner slope is not. Increase Δx\Delta x and watch the actual Δy\Delta y leave the linear prediction.

Common mistakes

Evaluating f′f' at xx instead of g(x)g(x). Forgetting the inner factor: (sin⁡x2)′=cos⁡(x2)⋅2x(\sin x^2)'=\cos(x^2)\cdot2x, not cos⁡(x2)\cos(x^2). Treating dy/du⋅du/dxdy/du\cdot du/dx as cancelling fractions without the differentiability conditions that make it valid.

Numerical considerations

Long chains multiply many factors. Factors with magnitude below 11 shrink the product toward zero, factors above 11 inflate it — the vanishing and exploding gradients of deep networks. In binary64 the product can underflow or overflow even when each factor is ordinary, which is why implementations often work with logarithms or normalised quantities (VII.7).

Engineering and ML connections

Every layer of a neural network is a stage uk+1=gk(uk)u_{k+1}=g_k(u_k); the gradient of the loss with respect to an early parameter is a chain-rule product through all later layers. The same rule propagates measurement uncertainty through a sequence of formulas and units through a pipeline of conversions.

Exercises

calculation

Multiply local factors

g(x) = x² and f(u) = 3u + 1. Give (f∘g)′(2).

calculation

Evaluate at the right place

g(x) = x², f(u) = u³. Give f′(g(1)) and (f∘g)′(1).

calculation

Propagate a small change

At some x, g′(x) = 2 and f′(g(x)) = −3. Estimate Δy when Δx = 0.01.

prediction

A common error

For h(x) = sin(x²), which is correct?

Choose one answer

prediction

Toward computational graphs

In y = f(g(x)), why is it efficient to multiply from the output backward?

Choose one answer

Summary and checkpoints

For nested functions, local rates multiply: h′(x)=f′(g(x)) g′(x)h'(x)=f'(g(x))\,g'(x), with the outer derivative evaluated at the intermediate value. The backward product of local factors is the seed of automatic differentiation. Next, III.7 lets a function depend on two inputs at once.

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