Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsCalculus

Rates of change and the derivative

P1.C140 min●○○ BeginnerReviewed Nov 30, 2026

Why this matters for machine learning

The derivative says how much a function's output changes when its input is nudged. Training a model means nudging its weights to lower the loss, so the derivative of the loss with respect to each weight tells you which way to nudge and how strongly.

  • Gradient descent moves each weight against the derivative of the loss: new weight = old weight −- learning rate ×\times derivative. (P1.F3: Gradient descent)
  • Backpropagation is an efficient way to find the derivative of the loss with respect to every weight in a network. (P4.8: Backpropagation: step by step with numbers)
  • Where the sigmoid or tanh is flat, its derivative is almost 0, so the learning signal passing back through it nearly vanishes (the vanishing-gradient problem). (P4.16: Vanishing and exploding gradients, coming soon)
  • Gradient checking tests backprop code by nudging a weight a tiny bit, watching the loss change, and comparing that slope with the computed derivative. (P4.8: Backpropagation: step by step with numbers)
  • Automatic differentiation, the engine inside deep-learning libraries, computes derivatives of whole programs with exact rules instead of nudging. (P1.C10: Computational graphs and automatic differentiation)

Before this: Functions and graphs, Exponents and logarithms, The sigmoid, tanh and other squashing functions

After this lesson you can

  • Compute an average rate of change Δy/Δx\Delta y/\Delta x and the slope of a secant line, and say what its units are
  • Explain the derivative as the limit of f(a+h)−f(a)h\frac{f(a+h)-f(a)}{h} as hh shrinks towards 0, and why we never just put h=0h=0
  • Use “zoom in until it looks straight” and the tangent-line approximation f(a+h)≈f(a)+f′(a) hf(a+h)\approx f(a)+f'(a)\,h, and say how fast its error shrinks
  • Read the sign and size of f′f', write f′(x)f'(x) and dydx\frac{dy}{dx} correctly, and derive x2x^2 and x3x^3 from the definition
  • Estimate a derivative with forward and central differences, explain why the error first falls and then rises as hh shrinks, and use this for gradient checking
  • Say where a derivative does not exist (a corner, a jump, a vertical tangent) and how ReLU at 0 is handled in practice

A car’s speedometer says 52 km/h. But speed is distance divided by time, and at one single instant no time has passed and no distance has been covered. So what does “52 right now” mean?

The answer is the idea of this lesson, and it is also the central question of machine learning: if I nudge this one number a tiny bit, how much does the result change? A model has weights, and the loss measures how wrong it is. If raising a weight by 0.01 makes the loss fall by 0.1, we should raise the weight. The exact change per unit of nudge is the derivative.

Average rate of change

Start with something you can compute. A toy car starts at rest and speeds up. Its distance from the start after tt seconds is d(t)=t2d(t)=t^2 metres. At t=1t=1 it has gone 1 m; at t=3t=3 it has gone 9 m. Over those two seconds it covered 8 m, so its average speed was

ΔdΔt=d(3)−d(1)3−1=9−12=4 m/s.\frac{\Delta d}{\Delta t}=\frac{d(3)-d(1)}{3-1}=\frac{9-1}{2}=4 \text{ m/s}.

(Δ\Delta, the Greek capital delta, means “the change in”.) For any function y=f(x)y=f(x), the average rate of change between two inputs is the change in output divided by the change in input:

ΔyΔx=f(x2)−f(x1)x2−x1.\frac{\Delta y}{\Delta x}=\frac{f(x_2)-f(x_1)}{x_2-x_1}.

Its unit is “output units per input unit”: metres per second here, or “loss per unit of weight” for a model.

An average hides detail. The car was slower than 4 m/s early on and faster later. Shorter stretches tell more:

from tt to ttdistance gainedaverage speed
1 to 39−1=89-1=844
1 to 24−1=34-1=333
1 to 1.52.25−1=1.252.25-1=1.252.52.5
1 to 1.11.21−1=0.211.21-1=0.212.12.1

As the stretch shrinks, the average speed settles towards 2 m/s. That number is the speed at t=1t=1. Making this precise is the whole lesson.

The same idea for a loss

Take the three-example model from P0.2: the prediction is y^=w x\hat{y}=w\,x (with b=0b=0), the data are (x,y)=(1,2),(2,3),(3,7)(x,y)=(1,2),(2,3),(3,7), and the loss is the mean squared error L(w)\mathcal{L}(w). At w=1w=1 the loss is 66. P0.2 raised ww to 1.011.01 and found a loss of about 5.90055.9005. The average rate of change of the loss between those two weights is

ΔLΔw=5.9005−61.01−1≈−9.95 loss units per unit of w.\begin{gathered} \frac{\Delta\mathcal{L}}{\Delta w}=\frac{5.9005-6}{1.01-1} \\ \approx-9.95 \text{ loss units per unit of } w. \end{gathered}

The negative sign says that raising ww lowers the loss. P0.2 promised that a smaller nudge gives the exact value, −10-10. Section “A derivative of a loss” below keeps that promise.

The secant line

Draw the graph of ff and pick two points on it: (a,f(a))(a,f(a)) and (a+h,f(a+h))(a+h,f(a+h)). The straight line through them is a secant line. Its slope is the average rate of change over the stretch from aa to a+ha+h, and it has a name, the difference quotient:

f(a+h)−f(a)h.\frac{f(a+h)-f(a)}{h}.

Here hh is the step: how far the second point is from the first. It can be negative too (the second point is then on the left of aa); the formula does not change.

Let f(x)=x2f(x)=x^2 and a=1a=1. The two points are (1,1)(1,1) and (1+h,(1+h)2)(1+h,(1+h)^2):

step hhsecond pointsecant slope
1(2, 4)(2,\,4)4−11=3\frac{4-1}{1}=3
0.5(1.5, 2.25)(1.5,\,2.25)2.52.5
0.1(1.1, 1.21)(1.1,\,1.21)2.12.1
0.01(1.01, 1.0201)(1.01,\,1.0201)2.012.01
0.001(1.001, 1.002001)(1.001,\,1.002001)2.0012.001
−0.1-0.1(0.9, 0.81)(0.9,\,0.81)1.91.9

The slope is 2+h2+h every time. Bring the second point closer, from either side, and the secant slope closes in on 2.

From secant to tangent: the limit

Why does the table say 2+h2+h every time? Expand (1+h)2=1+2h+h2(1+h)^2=1+2h+h^2, so

(1+h)2−1h=2h+h2h=2+h(h≠0).\begin{aligned} \frac{(1+h)^2-1}{h}&=\frac{2h+h^2}{h} \\ &=2+h \qquad (h\ne0). \end{aligned}

We want the slope “at” the point, with the two points on top of each other. But h=0h=0 gives 00\frac{0}{0}, which has no value: one point has no slope, because rise and run are both 0. The way out is a limit. We simplify first (this is allowed because h≠0h\ne0), and then ask what the simplified expression approaches as hh gets closer and closer to 0. Here it approaches 2. We write

lim⁡h→0 (2+h)=2.\lim_{h\to0}\,(2+h)=2.

A limit asks “what number do the values head towards?”, not “what is the value at h=0h=0?”. The value at h=0h=0 is not even needed.

The derivative of ff at aa is the limit of the secant slopes:

f′(a)=lim⁡h→0f(a+h)−f(a)h.f'(a)=\lim_{h\to0}\frac{f(a+h)-f(a)}{h}.

Read f′(a)f'(a) as “f prime of a”. If the limit exists (it has to be the same whether hh shrinks from the right or from the left), we say ff is differentiable at aa. The line through (a,f(a))(a,f(a)) with slope f′(a)f'(a) is the tangent line:

y=f(a)+f′(a) (x−a).y=f(a)+f'(a)\,(x-a).

So for x2x^2 at a=1a=1: f′(1)=2f'(1)=2, and the toy car’s speed at t=1t=1 is exactly 2 m/s. The speedometer answer to the opening puzzle is a limit of average speeds over shorter and shorter stretches.

Go deeper What the word limit means exactly

“The values head towards LL” can be made exact. We write lim⁡h→0g(h)=L\lim_{h\to0}g(h)=L when we can make g(h)g(h) as close to LL as we like by taking hh small enough, and h≠0h\ne0. In symbols: for every tolerance ε>0\varepsilon>0 there is a distance δ>0\delta>0 such that ∣g(h)−L∣<ε|g(h)-L|<\varepsilon whenever 0<∣h∣<δ0<|h|<\delta (both signs of hh count).

For g(h)=2+hg(h)=2+h and L=2L=2: ∣g(h)−L∣=∣h∣|g(h)-L|=|h|, so the choice δ=ε\delta=\varepsilon works. To get within 0.0010.001 of 2, take ∣h∣<0.001|h|<0.001. The condition 0<∣h∣0<|h| is where “never put h=0h=0” lives in the definition.

For a general ff the values g(h)=f(a+h)−f(a)hg(h)=\frac{f(a+h)-f(a)}{h} do not always settle on a single number. At a corner they head to two different numbers, one from each side, and then the limit does not exist. That case is in the section “Where there is no derivative”.

Zoom into a curve: secant, tangent and derivative

f(x) = x²

−3.515.54.381−2.38aa + htangentsecant

Still visibly curved: in this view the curve is up to 740 pixels away from its tangent line. Zoom in more.

a = 1, f(a) = 1; second point: a + h = 2, f(a + h) = 4
secant slope = (f(a + h) − f(a)) / h = (4 − 1) / 1 = 3
derivative f′(a) = 2
secant slope − derivative = 1
view: x from −3.5 to 5.5, zoom ×1
largest gap between the curve and its tangent in this view: 740 pixels

The dark curve is the function; the blue dot is the point a. The pink line is the secant through a and a + h (pink dot). The orange band is the tangent: the line with slope f′(a). The grid squares are a quarter of the view width wide, and the numbers on the edges show the x and y range. Both axes use the same scale, so a slope of 1 always looks like 45°.

Zoom into a curve. The pink secant runs through a and a + h; the orange band is the tangent. The Zoom slider (up to a million times) shrinks the view around a. Smooth curves end up on top of their tangent; |x|, ReLU, the cube root and the step at 0 do not.

Things to try with the zoom widget:

  1. Keep x2x^2 at a=1a=1 and move hh from 1 down to 10−610^{-6}. The secant slope goes 3, 2.1, 2.01,…3,\ 2.1,\ 2.01,\dots and the line swings onto the orange tangent. The last readout, “secant slope −- derivative”, is about 2+h−2=h2+h-2=h here (for the tiniest hh, round-off in the subtraction changes the last digits).
  2. Put hh back to 1 and slide Zoom up. The parabola bends away from the tangent a lot at ×1, but at about ×1000 (×10 000 on a wide screen) the largest gap between them is under a pixel on a phone-sized widget. This is the next section.
  3. Choose ex\mathrm{e}^x and look at the derivative at a=1a=1: it is 2.718…2.718\ldots, the same as the height f(a)f(a). Choose the sigmoid at a=2a=2: the derivative is 0.1050.105. Slide aa to 6, where the sigmoid is nearly flat: the derivative is about 0.00250.0025 (the slider for aa reaches ±6\pm6 for the sigmoid and ±3\pm3 for the others).
  4. Choose ∣x∣|x|, where aa starts at 0. Zoom in as far as you like: the corner stays. The right-hand secant slope is +1+1 and the left-hand one is −1-1. Now move aa to 0.05 and zoom in to ×1000 or more: the corner is out of view, and the curve looks straight again.

Zooming in: a curve is almost a straight line

Look at a small enough piece of a smooth curve and it looks straight, the way a small piece of the Earth looks flat. This is the picture to keep: near aa, the curve is well described by its tangent line. The widget lets you check it: the gap between curve and tangent, measured in pixels, shrinks as you zoom.

(Where the Earth analogy breaks: the Earth is not flat, and a curve never becomes exactly straight. It only gets closer and closer to its tangent, compared with the size of the view. The tangent line is the best straight-line description near aa, not an exact one.)

In symbols, near aa we can replace the curve by the line:

f(a+h)≈f(a)+f′(a) h.f(a+h)\approx f(a)+f'(a)\,h.

(Read it as: start at f(a)f(a), and add “slope times the step”.) For f(x)=x2f(x)=x^2 and a=1a=1 we have f(1)=1f(1)=1 and f′(1)=2f'(1)=2, so the approximation is 1+2h1+2h. The exact value is (1+h)2=1+2h+h2(1+h)^2=1+2h+h^2. Compare:

step hhapproximation 1+2h1+2hexact (1+h)2(1+h)^2error
0.522.250.25
0.11.21.210.01
0.011.021.02010.0001
0.0011.0021.0020010.000001

For this function the error is exactly h2h^2. Cut hh by 10 and the error falls by 100. The error divided by hh is 0.5, 0.1, 0.01, 0.0010.5,\ 0.1,\ 0.01,\ 0.001 in the four rows: it goes to 0, and that is what “looks straight when you zoom in” means: the error is tiny even compared with the small step. (For ex\mathrm{e}^x at a=0a=0, where f′(0)=1f'(0)=1, the error of 1+h1+h is about h2/2h^2/2: 0.00520.0052 at h=0.1h=0.1 and 0.0000500.000050 at h=0.01h=0.01.)

This approximation is what gradient descent relies on (P1.F3). From x=3x=3 on f(x)=x2f(x)=x^2 the slope is 6. A step of −0.6-0.6 (η=0.1\eta=0.1) is predicted to land at 9−6×0.6=5.49-6\times0.6=5.4. The true value is f(2.4)=5.76f(2.4)=5.76. The prediction is decent here, but its error, 0.36=h20.36=h^2, grows quickly as steps grow. That is one reason the learning rate cannot be too big. The size of the correction comes from the curvature of ff, the second derivative (P1.C8).

Go deeper What differentiable means, in one line

A function is differentiable at aa exactly when the tangent-line approximation has an error r(h)r(h) with r(h)/h→0r(h)/h\to0:

f(a+h)=f(a)+f′(a) h+r(h),r(h)h→0 as h→0.\begin{aligned} f(a+h)&=f(a)+f'(a)\,h \\ &\quad+r(h), \\ \frac{r(h)}{h}&\to0 \text{ as } h\to0. \end{aligned}

This is the zoom picture in symbols: the curve minus its tangent is small even compared with hh. It also shows that a function differentiable at aa has no jump there: as h→0h\to0, f(a+h)−f(a)=f′(a) h+r(h)→0f(a+h)-f(a)=f'(a)\,h+r(h)\to0. The reverse fails. ∣x∣|x| has no jump at 0 and still no derivative there.

Notation: four ways to write one thing

All of these mean “the derivative”:

  • f′(x)f'(x) (“f prime of x”): short, used when the function has a name. f′(a)f'(a) is the derivative at the particular point aa.
  • dfdx\dfrac{df}{dx}, or dydx\dfrac{dy}{dx} when y=f(x)y=f(x): the “derivative of ff with respect to xx”. It comes from ΔyΔx\frac{\Delta y}{\Delta x}, with Δ\Delta replaced by dd for “a tiny change”.
  • ddxf(x)\dfrac{d}{dx}f(x): “apply the derivative with respect to xx to f(x)f(x)”. For example, ddxx2=2x\frac{d}{dx}x^2=2x.
  • dfdx∣x=a\left.\dfrac{df}{dx}\right|_{x=a}: the value of dfdx\frac{df}{dx} at x=ax=a. It equals f′(a)f'(a).

For now, read dydx\frac{dy}{dx} as one symbol, not as the fraction “dy divided by dx” that you can split up or cancel. The derivative is a limit of fractions, and dydy and dxdx alone have not been given a meaning here. (Later, with the chain rule in P1.C3, dydx\frac{dy}{dx} will often behave like a ratio, which is part of why this notation is so convenient.) In machine learning you will write L′(w)\mathcal{L}'(w) or dLdw\frac{d\mathcal{L}}{dw} for a loss with one parameter, and the curly ∂L∂w\frac{\partial\mathcal{L}}{\partial w} for a loss with many (partial derivatives, P1.C4).

The derivative has units: output units per input unit. If dd is in metres and tt in seconds, d′d' is in metres per second. If L\mathcal{L} is a loss and ww a weight, L′(w)\mathcal{L}'(w) is “loss per unit of weight”.

The derivative is a function

For each input xx you get a slope f′(x)f'(x): so the derivative is itself a function. Let us find it for three functions, straight from the definition.

A straight line, f(x)=mx+cf(x)=mx+c. Then f(x+h)−f(x)=mhf(x+h)-f(x)=mh, so the difference quotient is mm for every hh and every xx, and f′(x)=mf'(x)=m. A line has the same slope everywhere. A constant function (m=0m=0) has derivative 0.

The square, f(x)=x2f(x)=x^2. Now (x+h)2−x2=2xh+h2(x+h)^2-x^2=2xh+h^2, so

(x+h)2−x2h=2xh+h2h=2x+h⟶ 2x(h→0).\begin{aligned} \frac{(x+h)^2-x^2}{h}&=\frac{2xh+h^2}{h}=2x+h\\ &\longrightarrow\ 2x \quad (h\to0). \end{aligned}

So f′(x)=2xf'(x)=2x. At x=1x=1 this is 2, as in the table. At x=3x=3 it is 6 (the slope used in the gradient-descent example of P1.F3), at x=0x=0 it is 0, and at x=−2x=-2 it is −4-4.

The cube, f(x)=x3f(x)=x^3. Expanding (x+h)3=x3+3x2h+3xh2+h3(x+h)^3=x^3+3x^2h+3xh^2+h^3 gives

(x+h)3−x3h=3x2+3xh+h2⟶ 3x2.\begin{aligned} \frac{(x+h)^3-x^3}{h}&=3x^2+3xh+h^2\\ &\longrightarrow\ 3x^2. \end{aligned}

So f′(x)=3x2f'(x)=3x^2, and f′(1)=3f'(1)=3.

You might spot a pattern (x2→2xx^2\to2x, x3→3x2x^3\to3x^2). Do not memorise it from two cases: P1.C2 collects the shortcut rules (power, sum, product, quotient, exponential, logarithm), so that you rarely have to go back to the limit. The definition is what those rules are built from, and what the numerical checks below test.

Two derivatives you were promised

The exponential. P1.A2 said that ex\mathrm{e}^x grows at a rate equal to its own value. Here is where that comes from:

ea+h−eah=ea⋅eh−1h.\frac{\mathrm{e}^{a+h}-\mathrm{e}^{a}}{h}=\mathrm{e}^{a}\cdot\frac{\mathrm{e}^{h}-1}{h}.

The factor eh−1h\frac{\mathrm{e}^h-1}{h} does not depend on aa. Numerically it is 1.05171.0517 at h=0.1h=0.1, 1.00501.0050 at h=0.01h=0.01, 1.00051.0005 at h=0.001h=0.001, and it approaches 1. So the derivative of ex\mathrm{e}^x is ex⋅1\mathrm{e}^x\cdot1. (That this limit is exactly 1 is how P1.C2 defines e\mathrm{e}; it also sketches why this agrees with the compound-interest definition of P1.A2.) For another base bb the same factor is bh−1h\frac{b^h-1}{h}. For b=2b=2 it approaches 0.6931…=ln⁡20.6931\ldots=\ln 2, which is the “ln⁡b\ln b times its value” of P1.A2.

The sigmoid. P1.A5 measured the slope of σ\sigma with h=0.01h=0.01 and told you to shrink it towards 0. Do it at z=2z=2:

step hhsecant slope of σ\sigma at z=2z=2
0.10.1011
0.010.1046
0.0010.10495
0.00010.10499

It approaches 0.104994…0.104994\ldots, which is σ(2) (1−σ(2))=0.8808×0.1192\sigma(2)\,(1-\sigma(2))=0.8808\times0.1192. This is the closed form σ′(z)=σ(z) (1−σ(z))\sigma'(z)=\sigma(z)\,(1-\sigma(z)) that P1.A5 gave you to check: at z=0z=0 it gives 0.250.25, the largest slope, and at z=6z=6 it gives 0.00250.0025, the flat tail. The same shrinking works for tanh: at z=2z=2 the secant slopes are 0.07000.0700 (h=0.01h=0.01, the value in P1.A5), 0.070580.07058 (h=0.001h=0.001) and 0.070640.07064 (h=0.0001h=0.0001), approaching 1−tanh⁡2(2)=0.070651…1-\tanh^2(2)=0.070651\ldots, the closed form tanh⁡′(z)=1−tanh⁡2(z)\tanh'(z)=1-\tanh^2(z) from P1.A5. P1.C2 derives both from its rules, and P1.C3 shows a shorter way with the chain rule.

What the derivative tells you

Sign. If f′(a)>0f'(a)>0, then ff is rising at aa (more input gives more output). If f′(a)<0f'(a)<0, it is falling. If f′(a)=0f'(a)=0, the graph is flat at aa for an instant.

Size. A large ∣f′(a)∣|f'(a)| means a steep graph: the output reacts strongly to the input. A small one means it hardly reacts (the sigmoid’s flat tails, P1.A5).

Use it to predict. The tangent-line approximation turns a slope into a forecast: if f′(2)=−3f'(2)=-3, then raising xx from 2 to 2.01 changes ff by about −3×0.01=−0.03-3\times0.01=-0.03.

A loss example. In P1.A1 a one-parameter model had the loss L(w)=(2w−6)2L(w)=(2w-6)^2. Write it as 4(w−3)24(w-3)^2. The algebra of x2x^2, with xx replaced by w−3w-3, gives L′(w)=8(w−3)=8w−24L'(w)=8(w-3)=8w-24:

wwL(w)L(w)L′(w)L'(w)what it says
036−24-24falling steeply: raise ww
24−8-8still falling, less steeply: raise ww
3000flat: the bottom of the bowl
4488rising: lower ww

This table is gradient descent in miniature (P1.F3): step against the sign of the slope, and take smaller steps where it is small.

Zero slope is not always a minimum. f′(a)=0f'(a)=0 marks a flat spot. For x2x^2 at 0 it is a minimum, for −x2-x^2 at 0 a maximum, and for x3x^3 at 0 neither: the slope 3x23x^2 is 0 there, but the curve keeps rising on both sides. Telling these apart is the job of the second derivative (P1.C8) and of P1.F2.

A derivative of a loss

Back to the loss of the three-example model. Put w=1+hw=1+h. The predictions are 1+h, 2+2h, 3+3h1+h,\,2+2h,\,3+3h, the errors are h−1, 2h−1, 3h−4h-1,\,2h-1,\,3h-4, and expanding the squares gives

L(1+h)−L(1)=−30h+14h23,L(1+h)−L(1)h=−10+143h.\begin{aligned} \mathcal{L}(1+h)-\mathcal{L}(1)&=\frac{-30h+14h^2}{3},\\ \frac{\mathcal{L}(1+h)-\mathcal{L}(1)}{h}&=-10+\frac{14}{3}h. \end{aligned}

At h=0.01h=0.01 this is −9.953-9.953, which is the −9.95-9.95 that P0.2 found. As h→0h\to0 it tends to −10-10, so L′(1)=−10\mathcal{L}'(1)=-10: a nudge of +0.001+0.001 in ww lowers the loss by about 0.010.01. The same steps for bb (with ww held at 1) give a slope of −4-4 at b=0b=0. Finding both slopes at once is the job of partial derivatives and the gradient (P1.C4, P1.C5).

Estimating a derivative with numbers

Often you cannot differentiate by hand, or you want to check a formula you derived. Then you estimate the slope from function values, using a small but not-zero hh. These estimates are called finite differences. Three versions:

  • Forward: f(x+h)−f(x)h\dfrac{f(x+h)-f(x)}{h} (look ahead).
  • Backward: f(x)−f(x−h)h\dfrac{f(x)-f(x-h)}{h} (look behind).
  • Central: f(x+h)−f(x−h)2h\dfrac{f(x+h)-f(x-h)}{2h} (look both ways, and divide by the full width 2h2h).

Test them on f(x)=x3f(x)=x^3 at x=1x=1, where the true slope is 3. Algebra gives the errors exactly:

  • forward: (1+h)3−1h=3+3h+h2\dfrac{(1+h)^3-1}{h}=3+3h+h^2, an error of 3h+h23h+h^2, about 3h3h for small hh;
  • central: (1+h)3−(1−h)32h=3+h2\dfrac{(1+h)^3-(1-h)^3}{2h}=3+h^2, an error of exactly h2h^2.
hhforward errorcentral error
0.10.310.01
0.010.0300.0001
0.0010.00300.000001

Shrink hh by 10 and the forward error shrinks by about 10, while the central error shrinks by 100. We say the forward difference has error of order hh, and the central difference of order h2h^2. The central one is better because the bends on the two sides of xx cancel (the Go-deeper box below shows how). For the square the cancellation is perfect: the central difference of x2x^2 is exactly 2x2x for every hh in exact arithmetic.

But a smaller hh is not always better

The table suggests we should take hh as tiny as possible. The computer disagrees. It stores numbers with about 16 significant digits (64-bit floating point). When hh is tiny, f(x+h)f(x+h) and f(x)f(x) agree in nearly all of those digits, and their difference keeps only a few digits that are mostly rounding noise. Dividing by a tiny hh then multiplies the noise. Here are real results for x3x^3 at x=1x=1, computed in Python with ordinary floats (the algebra above holds only for exact arithmetic):

hhforward errorcentral error
10−110^{-1}3.1×10−13.1\times10^{-1}1.0×10−21.0\times10^{-2}
10−310^{-3}3.0×10−33.0\times10^{-3}1.0×10−61.0\times10^{-6}
10−510^{-5}3.0×10−53.0\times10^{-5}9.7×10−119.7\times10^{-11}
10−810^{-8}4.0×10−94.0\times10^{-9}7.1×10−97.1\times10^{-9}
10−1010^{-10}2.5×10−72.5\times10^{-7}2.5×10−72.5\times10^{-7}
10−1210^{-12}2.7×10−42.7\times10^{-4}1.0×10−41.0\times10^{-4}
10−1410^{-14}2.4×10−32.4\times10^{-3}2.4×10−32.4\times10^{-3}
10−1610^{-16}331.31.3

The error falls, reaches a bottom, and then climbs again: a U shape on a log scale. At h=10−16h=10^{-16} the number 1+10−161+10^{-16} is rounded to exactly 11, so f(x+h)−f(x)=0f(x+h)-f(x)=0 and the forward estimate of the slope is 00, an error of 3. For x3x^3 these digits are the same on any machine with standard 64-bit floats, because only ++, −-, ×\times and ÷\div are involved; another function, or a library ex\mathrm{e}^x or sin⁡x\sin x, gives similar sizes, not necessarily the same digits.

The best hh depends on the method: for this function, about 10−810^{-8} for the forward difference (error about 4×10−94\times10^{-9}), and about 10−510^{-5} to 10−610^{-6} for the central difference (error about 10−1110^{-11}). Rules of thumb from error analysis, for functions with values and derivatives of ordinary size: roughly the square root of the machine epsilon (2.2×10−162.2\times10^{-16}, the gap between 1 and the next float) for the forward difference, which is about 1.5×10−81.5\times10^{-8}, and its cube root, about 6×10−66\times10^{-6}, for the central difference.

Go deeper Why the central difference is better, and where the best step size comes from

Near xx, a smooth function is a polynomial plus smaller corrections (Taylor’s idea, covered properly in P1.C8):

f(x±h)=f(x)±f′(x) h+12f′′(x) h2±16f′′′(x) h3+⋯\begin{aligned} f(x\pm h)&=f(x)\pm f'(x)\,h \\ &\quad+\tfrac12 f''(x)\,h^2 \\ &\quad\pm\tfrac16 f'''(x)\,h^3+\cdots \end{aligned}

Subtract to get the forward estimate: it equals f′(x)+12f′′(x) h+⋯f'(x)+\tfrac12 f''(x)\,h+\cdots, so its error is about 12∣f′′∣ h\tfrac12|f''|\,h (order hh). In the central estimate the terms in h2h^2 cancel, because they have the same sign on both sides: it equals f′(x)+16f′′′(x) h2+⋯f'(x)+\tfrac16 f'''(x)\,h^2+\cdots, an error of order h2h^2. For x3x^3 at x=1x=1 we have f′′=6f''=6 and f′′′=6f'''=6, giving 3h3h and h2h^2, as in the table.

Round-off adds a second error. Each stored value of ff is off by a relative amount of roughly u≈1.1×10−16u\approx1.1\times10^{-16}, so the numerator is off by about u∣f∣u|f| and the estimate by about u∣f∣/hu|f|/h. Total error is therefore roughly (truncation, growing with hh) plus (round-off, growing as hh shrinks). Setting the two equal gives hh near u\sqrt{u} for the forward difference and near u1/3u^{1/3} for the central one, up to constants that depend on ff. These are rules of thumb, not guarantees.

Finite differences: how small should h be?

−16−14−12−10−8−6−4−2−15−10−50log₁₀ hlog₁₀ error

● forward difference error · ● central difference error · dashed: rough size of the truncation errors (blue, pink) and of the round-off (grey)

h = 0.01
true derivative f′(1) = 3 for f(x) = x³, x = 1
forward: (f(x + h) − f(x)) / h = 3.0301
forward error = 3.01×10⁻²
central: (f(x + h) − f(x − h)) / (2h) = 3.0001
central error = 1×10⁻⁴
smallest error on this plot: forward 3.97×10⁻⁹ at h = 1×10⁻⁸; central 4.98×10⁻¹² at h = 3.16×10⁻⁶

Forward: the error is no bigger than about the truncation error (the curve bending away from the straight line). Round-off is not the main part here.

Central: the error is no bigger than about the truncation error (the curve bending away from the straight line). Round-off is not the main part here.

Values are computed with ordinary 64-bit floating-point numbers, the same as Python floats. The errors are measured against the exact derivative. If an error is exactly 0 it cannot be shown on a log scale, so it is drawn at the bottom edge.

Finite-difference error explorer. Error of the forward (blue) and central (pink) difference against h, for h from 10 to the power −1 down to 10 to the power −16 (log scales). The slider moves the marker; the readouts show which cause of error dominates.

Things to try with the error explorer:

  1. With x3x^3 at x=1x=1, slide kk from 1 to 16. Watch the blue (forward) line fall with a slope of 1 on the log–log plot (a factor of 10 in hh gives a factor of 10 in error) and the pink (central) line fall twice as fast, until both are lifted by round-off. The status lines change from “truncation” to “round-off” as you cross the bottom.
  2. Find the best kk for each method: about 8 for forward, between 5 and 6 for central.
  3. Go to k=16k=16: x+hx+h is the same number as xx, so the forward estimate is 00. Then try ex\mathrm{e}^x, sin⁡x\sin x and the sigmoid at x=1x=1: the bottoms of the U move a little, but the shape stays. (The sigmoid is used at x=1x=1 because at x=0x=0 it is symmetric and its forward and central differences come out the same.)

Gradient checking

This is the main use of finite differences in machine learning. Suppose you derived a gradient by hand, or you wrote backprop code (P4.8). To test it, compare with a central difference of the loss: nudge one weight up and down by a small hh (often 10−510^{-5} to 10−710^{-7} in 64-bit floats), recompute the loss each time, and see whether the slope matches. If the two disagree by more than rounding noise (compare the relative difference), there is a bug. The test costs two loss evaluations per weight, far too slow for training, so it is used for debugging. Automatic differentiation (P1.C10) finds exact derivatives with rules instead of an hh to choose.

Where there is no derivative

The derivative needs the secant slopes to settle on one number, from the right and from the left. Three ways this can fail.

A corner. f(x)=∣x∣f(x)=|x| at 0. From the right, the secant slope is ∣h∣−0h=+1\frac{|h|-0}{h}=+1 for every h>0h>0. From the left, with h<0h<0, it is ∣h∣−0h=−1\frac{|h|-0}{h}=-1. The two sides head to different numbers, so the limit does not exist, and neither does f′(0)f'(0). Zooming does not help: the curve is a corner at every scale (try it in the zoom widget). At every other point, ∣x∣|x| has a derivative: +1+1 for x>0x>0, −1-1 for x<0x<0.

ReLU is the same kind of corner: ReLU(x)=max⁡(0,x)\mathrm{ReLU}(x)=\max(0,x) has slope 00 from the left and 11 from the right at x=0x=0. So it has no derivative at 0, and yet networks full of ReLU are trained with gradient descent. A library simply picks a value at that single point. For PyTorch (checked with version 2.9.1) the gradient of ReLU at exactly 0 is 0, and so is the gradient of ∣x∣|x| at 0 (the sign of 0 is 0). Other libraries may choose differently. Finite-difference checks are no help at a corner: the central difference of ∣x∣|x| at 0 is exactly 00, and that of ReLU is 0.50.5, neither of which is a derivative. So do not trust a gradient check at such a point.

A jump. The step function (00 for x<0x<0, 11 for x≥0x\ge0) at 0: from the right the secant slope is 0, but from the left it is 1/∣h∣1/|h|, which grows without limit as ∣h∣|h| shrinks. Away from 0, its derivative is 0 everywhere: a flat piece has no slope to follow. This is why a step activation gives gradient-based training nothing to follow, and why smooth curves like the sigmoid replaced it in networks trained this way (P1.A5, P4.4).

A vertical tangent. f(x)=x3f(x)=\sqrt[3]{x} at 0: the secant slope is h3h=h−2/3\frac{\sqrt[3]{h}}{h}=h^{-2/3}, which is 100100 at h=0.001h=0.001 and 10 00010\,000 at h=10−6h=10^{-6}. It grows without limit. The tangent is a vertical line, and its “slope” is infinite, so there is no derivative.

In short: a function can be defined and even continuous at a point and still have no derivative there (corner, vertical tangent). It cannot have a derivative where it jumps.

The derivative in three depths

Intuition

The derivative is the speedometer reading: not an average over a trip, but the rate right now. You get it by measuring average rates over shorter and shorter stretches until they stop changing. Zoomed in, a smooth curve is a straight line, and the derivative is that line’s slope.

For a model, the derivative of the loss with respect to a weight is the answer to “if I nudge this weight up a tiny bit, how much does the loss change per unit of nudge?”. Negative means the loss falls, large means it reacts strongly.

Math

ΔyΔx=f(a+h)−f(a)h,f′(a)=lim⁡h→0f(a+h)−f(a)h.\begin{gathered} \frac{\Delta y}{\Delta x}=\frac{f(a+h)-f(a)}{h}, \\ f'(a)=\lim_{h\to0}\frac{f(a+h)-f(a)}{h}. \end{gathered}

Tangent line: y=f(a)+f′(a) (x−a)y=f(a)+f'(a)\,(x-a). Local linear approximation: f(a+h)≈f(a)+f′(a) hf(a+h)\approx f(a)+f'(a)\,h, with an error r(h)r(h) for which r(h)/h→0r(h)/h\to0.

From the definition: (mx+c)′=m(mx+c)'=m, (x2)′=2x(x^2)'=2x, (x3)′=3x2(x^3)'=3x^2.

Finite differences: forward f(x+h)−f(x)h\frac{f(x+h)-f(x)}{h} (error of order hh) and central f(x+h)−f(x−h)2h\frac{f(x+h)-f(x-h)}{2h} (error of order h2h^2), plus round-off of order u∣f∣/hu|f|/h with u≈1.1×10−16u\approx1.1\times10^{-16} in 64-bit floats.

No derivative where the one-sided slopes differ (corner), grow without limit (jump, vertical tangent).

Code

def derivative(f, x, h=1e-5):
    """Central-difference estimate of f'(x)."""
    return (f(x + h) - f(x - h)) / (2 * h)

derivative(lambda x: x * x, 3.0)   # about 6

PyTorch finds exact derivatives with automatic differentiation (P1.C10). This runs in Colab or on your machine, not in the browser here:

import torch
x = torch.tensor(1.0, requires_grad=True)
y = x ** 3
y.backward()      # computes dy/dx
print(x.grad)     # tensor(3.)

Try it: shrinking steps and the U-shaped error

The first cell shrinks hh for x2x^2 and for the sigmoid. The second builds the U-shaped table above and shows the ReLU corner. Change the numbers and predict the output before you run it.

Try it: secant slopes close in on the derivative

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Challenge: change a to −2-2 and predict the derivative of x2x^2 there before running.

Try it: forward and central differences, and a corner

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Challenge: use ex\mathrm{e}^x (math.exp) at x=1x=1 and find the hh with the smallest central error. The true slope is math.exp(1).

Common mistakes

Check your understanding

  1. A toy car has distance d(t)=t2d(t)=t^2 metres after tt seconds. What is its average speed between t=1t=1 and t=3t=3?

  2. Why do we not find f′(a)f'(a) by putting h=0h=0 into f(a+h)−f(a)h\frac{f(a+h)-f(a)}{h}?

  3. You know that f′(2)=−3f'(2)=-3. Using the tangent-line approximation, about how much does ff change when xx goes from 2 to 2.01?

  4. You estimate a derivative with a central difference in 64-bit floating point, for a function whose values and derivatives are of ordinary size (around 1). Which step hh is the best choice?

  5. At x=0x=0, ReLU has slope 0 from the left and slope 1 from the right. What does this tell you about its derivative at 0?

Exercises

  1. For d(t)=t2d(t)=t^2, find the average speed between t=2t=2 and t=2.5t=2.5, and then the speed at t=2t=2 from the definition.
    Show answerAverage: (6.25−4)/0.5=4.5(6.25-4)/0.5=4.5 m/s. The difference quotient at t=2t=2 is (2+h)2−4h=4+h\frac{(2+h)^2-4}{h}=4+h, which tends to 4, so the speed at t=2t=2 is 4 m/s.
  2. For f(x)=x2f(x)=x^2 at a=3a=3, write the difference quotient, the derivative, and the tangent line. Use the tangent line to estimate 3.0123.01^2.
    Show answerThe quotient is (3+h)2−9h=6+h\frac{(3+h)^2-9}{h}=6+h, so f′(3)=6f'(3)=6 and the tangent is y=9+6(x−3)=6x−9y=9+6(x-3)=6x-9. At x=3.01x=3.01 it gives 9.069.06. The exact value is 9.06019.0601, so the error is 0.0001=h20.0001=h^2.
  3. Using the definition, find f′(2)f'(2) for f(x)=x3f(x)=x^3.
    Show answer(2+h)3−8h=12+6h+h2→12\frac{(2+h)^3-8}{h}=12+6h+h^2\to12, so f′(2)=12f'(2)=12 (this agrees with 3x23x^2 at x=2x=2).
  4. Using the definition, find the derivative of f(x)=1/xf(x)=1/x at a=2a=2.
    Show answer1h(12+h−12)=1h⋅2−(2+h)2(2+h)=−12(2+h)→−14\frac{1}{h}\left(\frac1{2+h}-\frac12\right)=\frac1h\cdot\frac{2-(2+h)}{2(2+h)}=\frac{-1}{2(2+h)}\to-\frac14. So f′(2)=−0.25f'(2)=-0.25 (the slope is negative: 1/x1/x falls as xx grows).
  5. For the loss L(w)=(2w−6)2L(w)=(2w-6)^2 with L′(w)=8w−24L'(w)=8w-24, find the slope at w=1w=1. Which way should ww move, and what happens to LL for a nudge of +0.01+0.01?
    Show answerL′(1)=8−24=−16L'(1)=8-24=-16: the loss is falling, so raise ww. A nudge of +0.01+0.01 changes LL by about −16×0.01=−0.16-16\times0.01=-0.16. (Exactly: L(1.01)=15.8404L(1.01)=15.8404 against L(1)=16L(1)=16, a change of −0.1596-0.1596.)
  6. Show that the central difference of f(x)=x2f(x)=x^2 at x=3x=3 with h=1h=1 equals the true derivative exactly. Why?
    Show answer42−222=16−42=6=f′(3)\frac{4^2-2^2}{2}=\frac{16-4}{2}=6=f'(3). In general (x+h)2−(x−h)2=4xh(x+h)^2-(x-h)^2=4xh, so the central difference is 4xh2h=2x\frac{4xh}{2h}=2x for every hh: the error terms cancel completely for a quadratic.
  7. Where does f(x)=∣x−2∣f(x)=|x-2| have no derivative, and what are the one-sided slopes there?
    Show answerAt x=2x=2 (the corner). The slope from the left is −1-1 and from the right is +1+1.
  8. In the second code cell, predict the forward estimate of the slope of x3x^3 at x=1x=1 with h=10−16h=10^{-16}, and explain it.
    Show answerIt is 00 (an error of 3). The number 1+10−161+10^{-16} rounds to exactly 11 in 64-bit floating point, so f(x+h)−f(x)=0f(x+h)-f(x)=0.
  9. A weight has L′(w)=−10\mathcal{L}'(w)=-10 (loss units per unit of weight) at the current value. About how much does the loss change if ww increases by 0.0020.002?
    Show answerAbout −10×0.002=−0.02-10\times0.002=-0.02 loss units: the loss falls by about 0.020.02.
  10. The sigmoid has slope 0.250.25 at z=0z=0. Estimate it with a central difference and h=10−5h=10^{-5} in code, and compare with σ(0)(1−σ(0))\sigma(0)(1-\sigma(0)).
    Show answerσ(10−5)−σ(−10−5)2×10−5≈0.25\frac{\sigma(10^{-5})-\sigma(-10^{-5})}{2\times10^{-5}}\approx0.25, and 0.5×0.5=0.250.5\times0.5=0.25.

Next: computing a derivative from the limit every time is slow. P1.C2 collects the rules for sums, products, quotients, powers, ex\mathrm{e}^x and ln⁡x\ln x, and P1.C3 shows how slopes multiply when functions are nested, which is the heart of backpropagation.

Key takeaways

  • The average rate of change of ff between xx and x+hx+h is Δy/Δx=f(x+h)−f(x)h\Delta y/\Delta x=\frac{f(x+h)-f(x)}{h}: the slope of the secant line through two points of the graph. Its unit is output units per input unit (metres per second, or loss per unit of weight).
  • The derivative at aa is what this slope approaches as hh shrinks towards 0: f′(a)=lim⁡h→0f(a+h)−f(a)hf'(a)=\lim_{h\to0}\frac{f(a+h)-f(a)}{h}. We never put h=0h=0 (that gives 0/00/0). We simplify for h≠0h\ne0 and see where the values head. The line through (a,f(a))(a,f(a)) with slope f′(a)f'(a) is the tangent.
  • Zoom into a smooth curve far enough and it looks like its tangent line. That is the tangent-line approximation f(a+h)≈f(a)+f′(a) hf(a+h)\approx f(a)+f'(a)\,h. For x2x^2 at a=1a=1 the error is exactly h2h^2, which shrinks faster than hh itself.
  • Notation: f′(x)f'(x), dfdx\frac{df}{dx} and ddxf(x)\frac{d}{dx}f(x) all mean the derivative as a function of xx. Read dydx\frac{dy}{dx} as one symbol (not as a fraction you can split) for now. From the definition: x2→2xx^2\to 2x and x3→3x2x^3\to3x^2.
  • The sign of f′f' says whether ff rises (>0>0) or falls (<0<0) there; its size says how steep. A zero slope is a flat spot, but it can be a minimum, a maximum or neither.
  • Finite differences estimate a derivative from function values: the forward difference has error about proportional to hh, the central difference f(x+h)−f(x−h)2h\frac{f(x+h)-f(x-h)}{2h} about proportional to h2h^2. In 64-bit floats, round-off takes over for tiny hh, so the error is U-shaped. Values near 10−510^{-5} to 10−610^{-6} suit the central difference for a function of ordinary size. This is how gradients from backprop are checked.
  • A derivative does not exist where the curve has a corner (∣x∣|x| and ReLU at 0), a jump, or a vertical tangent. A library must then pick a value by convention, and a finite-difference check is not trustworthy at that point.
Found a mistake? Tell us