Derivatives: rates of change

How fast is something changing, right now? The derivative answers that — and every differential equation is built from it.

⏱ 20 minNeeds: Chapter 13 simulations
In plain words

Your speedometer does not tell you how far you travelled; it tells you how fast your distance is changing at this instant. That instantaneous rate is the derivative. Geometrically it is the slope of the graph when you zoom in so far that the curve looks like a straight line.

You will learn
Level 1 · basicSlope and rate of change; the derivative as a limit Level 2 · standardFinite differences; Taylor; partial derivatives and gradient Level 3 · advancedThe chain rule as the engine of backpropagation
Simplest example first · walking at a steady speed

You walk 3 metres every second, so after $t$ seconds you are at $s(t) = 3t$ metres. Between any two moments the average speed is $$\frac{s(t+h) - s(t)}{h} = \frac{3(t+h) - 3t}{h} = \frac{3h}{h} = 3,$$ whatever $t$ and $h$ are. So the derivative is $s'(t) = 3$: the slope of the straight-line graph, "rise over run". Now switch to $s(t) = t^2$ (speeding up): the slope triangle changes size as you move — at $t = 1$ the secant slopes $2.1, 2.01, 2.001, \dots$ approach $2$. That limit is the derivative.

1. From average rate to instantaneous rate

Animation: a secant line through two points on a curve turns into the tangent line as the gap h shrinks.
Watch: The secant slope $\frac{f(x+h)-f(x)}{h}$ approaches the true derivative as $h \to 0$. The error shrinks with $h$.

If a car is at position $s(t)$ at time $t$, its average speed between $t$ and $t+h$ is $$\frac{\text{change in position}}{\text{change in time}} = \frac{s(t+h)-s(t)}{h}.$$ This is the slope of the secant line through two points of the graph. Now let the time gap $h$ shrink. The secant turns into the tangent, and the average speed becomes the instantaneous speed.

Definition · Derivative

The derivative of $f$ at $x$ is $$f'(x) = \frac{df}{dx}(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h},$$ provided this limit exists. If it does, $f$ is called differentiable at $x$. Every differentiable function is continuous, but not conversely ($|x|$ at $x=0$).

Stewart, Calculus: Early Transcendentals, 8th ed., Cengage (2016), chapter "Limits and Derivatives".
Secant becomes tangentshrink h and watch the slopes agree
f(x)secant (slope = average rate)tangent (slope = f′(x))
The secant through $(x, f(x))$ and $(x+h, f(x+h))$ has slope $\frac{f(x+h)-f(x)}{h}$. As $h\to 0$ it approaches the tangent slope $f'(x)$.

Rules you will use constantly

Function $f(x)$Derivative $f'(x)$Where it appears
$x^n$$n x^{n-1}$polynomials, energy $\tfrac12 m v^2$
$e^{ax}$$a\, e^{ax}$growth and decay — the reason $e$ is special
$\sin(ax)$, $\cos(ax)$$a\cos(ax)$, $-a\sin(ax)$waves, vibrations
$\ln x$$1/x$log-likelihood losses
$\tanh x$$1-\tanh^2 x$neural network activation
$\sigma(x)=\frac{1}{1+e^{-x}}$$\sigma(x)\,(1-\sigma(x))$sigmoid neuron

Together with linearity $(af+bg)' = af' + bg'$, the product rule $(fg)' = f'g + fg'$ and the chain rule (Section 5), these rules let you differentiate almost anything by hand.

Real world

Velocity is the derivative of position; acceleration is the derivative of velocity. The rate of a chemical reaction is the derivative of a concentration. In a petroleum reservoir, the flow of oil (Darcy's law) is proportional to the derivative of pressure with respect to position — oil flows from high pressure towards low pressure, faster where the pressure changes steeply.

2. Derivatives on a computer: finite differences

A computer cannot take a limit. It simply picks a small $h$ and computes a finite difference:

$$\underbrace{\frac{f(x+h)-f(x)}{h}}_{\text{forward difference}} \qquad\qquad \underbrace{\frac{f(x+h)-f(x-h)}{2h}}_{\text{central difference}}$$

How accurate are they? Taylor's theorem (Section 3) gives the answer: the forward difference has error proportional to $h$, the central difference proportional to $h^2$. Halving $h$ halves the first error but quarters the second. This error is called truncation error.

So why not take $h = 10^{-15}$? Because computers store numbers with about 16 significant digits (floating point). Subtracting two nearly equal numbers $f(x+h) - f(x)$ loses most of those digits, and dividing by a tiny $h$ magnifies the loss. This is round-off error, roughly $\varepsilon/h$ with $\varepsilon \approx 10^{-16}$. The simulation below computes both differences in real double-precision arithmetic in your browser.

The best step size is not the smallesterror of the derivative of sin x at x = 1
forward differencecentral differenceguides: slope 1 and slope 2
Read the plot from right to left. At first the error falls as $h$ shrinks (truncation error, straight lines of slope 1 and 2). Then it rises again — round-off takes over. The forward difference is best near $h \approx 10^{-8}$, the central difference near $h \approx 10^{-5}$.
Why this matters for SciML

The trade-off between truncation and round-off appears in every numerical method of this book. It is also one reason PINNs (Physics-Informed Neural Networks) use automatic differentiation instead of finite differences: automatic differentiation computes derivatives of a network exactly (up to round-off), with no $h$ at all.

3. Taylor's theorem: every smooth function is locally a polynomial

Zoom in on a smooth curve and it looks like a straight line (that is the derivative). Zoom in a little less and it looks like a parabola, then a cubic… Taylor's theorem makes this precise.

Theorem · Taylor's theorem with remainder

Suppose $f$ has $n+1$ continuous derivatives on an interval containing $a$ and $x$. Then $$f(x) = \underbrace{f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \dots + \frac{f^{(n)}(a)}{n!}(x-a)^n}_{T_n(x),\ \text{Taylor polynomial}} + R_n(x),$$ $$R_n(x) = \frac{f^{(n+1)}(\xi)}{(n+1)!}(x-a)^{n+1} \quad\text{for some } \xi \text{ between } a \text{ and } x.$$

Burden, Faires & Burden, Numerical Analysis, 10th ed., Cengage (2016), chapter 1 "Mathematical Preliminaries"; Stewart (2016), chapter "Infinite Sequences and Series".
Taylor polynomials hugging a curveraise the order; move the centre
f(x)Taylor polynomial Tₙ(x)
Near the centre the polynomial is excellent; far away it fails. For $\ln(1+x)$ it fails beyond $x = 1$ whatever the order — the Taylor series has a finite radius of convergence.
Example · Where the error of finite differences comes from

Taylor with $n = 1$: $f(x+h) = f(x) + h f'(x) + \tfrac{h^2}{2} f''(\xi)$. Rearranging, $$\frac{f(x+h)-f(x)}{h} - f'(x) = \frac{h}{2}f''(\xi) = O(h).$$ Doing the same for $f(x-h)$ and subtracting, the $f''$ terms cancel and the central difference error becomes $\frac{h^2}{6} f'''(\xi) = O(h^2)$. The notation $O(h^p)$ ("order $h^p$") means: bounded by a constant times $h^p$ for small $h$.

LeVeque, Finite Difference Methods for Ordinary and Partial Differential Equations, SIAM (2007), chapter 1.
Theorem · Mean value theorem

If $f$ is continuous on $[a,b]$ and differentiable on $(a,b)$, there is a point $c \in (a,b)$ with $$f'(c) = \frac{f(b)-f(a)}{b-a}.$$ Somewhere, the instantaneous rate equals the average rate. (If you averaged 60 km/h, at some moment the speedometer read exactly 60.)

Stewart (2016), chapter "Applications of Differentiation".

4. Several variables: partial derivatives and the gradient

Temperature in a room depends on position: $T(x, y)$. The partial derivative $\partial T/\partial x$ is the rate of change when you move in the $x$ direction only, holding $y$ fixed. Compute it exactly like an ordinary derivative, treating the other variables as constants.

Example

$T(x,y) = x^2 y + \sin y$. Then $\dfrac{\partial T}{\partial x} = 2xy$ and $\dfrac{\partial T}{\partial y} = x^2 + \cos y$.

Definition · Gradient

For $f(x_1,\dots,x_n)$, the gradient is the vector of partial derivatives $$\nabla f = \Big(\frac{\partial f}{\partial x_1}, \dots, \frac{\partial f}{\partial x_n}\Big).$$ It points in the direction in which $f$ increases fastest, and its length is that fastest rate.

Stewart (2016), chapter "Partial Derivatives".
In SciML

Training a neural network means making a loss $L(\theta)$ small, where $\theta$ holds millions of parameters. Gradient descent steps opposite to $\nabla L$ — downhill. Chapter 11 lets you watch it. And in a PDE (Partial Differential Equation) such as the heat equation $u_t = \alpha u_{xx}$, the subscripts are partial derivatives: $u_t = \partial u/\partial t$, $u_{xx} = \partial^2 u/\partial x^2$.

5. The chain rule — the engine of deep learning

Theorem · Chain rule

If $g$ is differentiable at $x$ and $f$ is differentiable at $g(x)$, then the composition $f(g(x))$ is differentiable at $x$ and $$\frac{d}{dx} f(g(x)) = f'(g(x))\, g'(x).$$ In Leibniz notation, with $y = f(u)$, $u = g(x)$: $\dfrac{dy}{dx} = \dfrac{dy}{du}\dfrac{du}{dx}$.

Stewart (2016), chapter "Differentiation Rules".
Example · one neuron

A neuron computes $y = \tanh(wx + b)$. Its sensitivity to the weight $w$ is, by the chain rule with $u = wx+b$: $$\frac{\partial y}{\partial w} = \tanh'(u)\cdot \frac{\partial u}{\partial w} = \big(1 - \tanh^2(wx+b)\big)\, x.$$ A deep network is a long composition, so its gradient is a long product of such factors. Computing that product efficiently, from the output backwards, is backpropagation (Rumelhart, Hinton & Williams, Nature 323, 1986, 533–536).

6. Try it in Python

Press Run. This reproduces the V-shaped error plot of Section 2 and checks a derivative computed by the chain rule.

import numpy as np
import matplotlib.pyplot as plt

f, df = np.sin, np.cos          # function and its exact derivative
x = 1.0
h = np.logspace(-16, 0, 200)    # step sizes from 1e-16 to 1

fwd = np.abs((f(x + h) - f(x)) / h - df(x))
cen = np.abs((f(x + h) - f(x - h)) / (2 * h) - df(x))

plt.loglog(h, fwd, label="forward  O(h)")
plt.loglog(h, cen, label="central  O(h^2)")
plt.xlabel("step h"); plt.ylabel("error"); plt.legend(); plt.grid(alpha=.3)
plt.title("Truncation vs round-off")
plt.show()

print("best h (forward):", h[np.argmin(fwd)])
print("best h (central):", h[np.argmin(cen)])

# chain rule check for a neuron y = tanh(w*x + b)
w, b, x0 = 0.7, -0.2, 1.5
exact = (1 - np.tanh(w * x0 + b) ** 2) * x0
approx = (np.tanh((w + 1e-6) * x0 + b) - np.tanh((w - 1e-6) * x0 + b)) / 2e-6
print("dy/dw chain rule:", exact, "  finite difference:", approx)

The forward difference has error $O(h)$. If you make $h$ ten times smaller (and round-off is still negligible), the error becomes roughly…

Right — error proportional to $h$. The central difference, $O(h^2)$, would become 100 times smaller.

What is $\dfrac{d}{dx}\, e^{-x^2}$?

Right: chain rule with $u = -x^2$, so $\frac{d}{dx}e^{u} = e^{u}\cdot u' = e^{-x^2}\cdot(-2x)$.

Key takeaways

Further reading