Calculus Primer
If we change a model's setting a little, does its error improve or get worse? Calculus gives us a way to describe that change and use it to decide what to adjust next.
22 sections · 20 questions · 4 coding challenges
The arrow keys move between sections too.
How Can We Measure Something That Keeps Changing?
BOTIE
In the seventeenth century, Newton and Leibniz developed calculus through work on changing quantities, tangents, and accumulation. Newton described quantities that flow and the rates at which they flow. His Method of Fluxions, published in English in 1736, gives us a historical way into the subject: motion makes a rate of change something we can picture.
We can compare two nearby positions, then ask what happens as the interval between them becomes smaller. That leads to a derivative, a local rate of change. Accumulating small contributions leads to an integral. For a model, the changing quantity may be its error, and the thing we adjust may be a weight. The derivative then tells us how a small adjustment is expected to change that error.
Sources for this history
Which Way Makes the Error Smaller?
Imagine turning a knob and watching an error meter. We want the error to fall but do not know the best setting. A small change could tell us which way the meter responds.
Calculus makes that question precise: how does one quantity respond when another changes?
Start at one setting
The curve shows illustrative errors at different settings. The dot marks where we are now. Knowing the current error does not yet tell us which direction to move.
Vertical: Error
Horizontal: Knob setting
A derivative answers the small-change question
We will measure change across an interval, then shrink that interval to define an instantaneous rate. For several parameters, we collect their partial derivatives into a gradient.
For a sequence of operations, we connect local responses using the chain rule. Each formula will have a concrete question to answer.
1. Change Between Two Points
Everything here rests on comparing two changes. An output changes as an input changes, and the question is always how much of the one you get for the other. On a straight line that comparison has a name, the slope, and you compute it from any two points by dividing the rise, how far up the line went between them, by the run, how far across.
slope = rise / runWorked example
Take a line through the points (2, 3) and (6, 11). Between them it ran 4 across, from 2 to 6, and rose 8, from 3 to 11.
run = 6 − 2 = 4
rise = 11 − 3 = 8
slope = 8 / 4 = 2Two units upward for every one unit across.
Written with the points as (x₁, y₁) and (x₂, y₂), that is the whole formula.
slope = (y₂ − y₁) / (x₂ − x₁)The sign carries meaning of its own. Had the line dropped between the two points the rise would come out negative, and so would the slope, so a downhill line has a negative slope. A flat line has a slope of zero, because it rises by nothing however far it runs. Those three cases, positive, negative and zero, are the whole vocabulary, and every later section reuses them.
Rise over run can be dragged. The two points below start at the worked pair, and the triangle between them remeasures as either moves.
Drag either point and watch rise over run remeasure.
2. Slope as a Rate
Now the reframing that turns a fact about a drawing into something worth having. A slope is not only a tilt. When the two axes carry units, rise over run carries units too, and the slope becomes a rate.
Worked example
Let the horizontal axis be time in hours and the vertical axis be distance in miles. Drive 100 miles in 2 hours, and the line from start to finish has a slope of
100 miles / 2 hours = 50 miles per hourRise over run is miles over hours, so the slope is the speed.
Notice what kind of number that is. It is an average across the whole trip. At no single moment did the speedometer have to read 50, since you may have been stopped at a light for part of it and doing 70 for the rest. An average across a stretch and a reading at an instant are different quantities, and closing the gap between them is the entire subject of the next three sections.
3. Measuring a Curve Across an Interval
A straight line has one slope everywhere, which is what made it easy. A curve does not. It might fall steeply in one place, flatten out, and climb somewhere else, so no single number describes its steepness. What we can still do is exactly what we did with the drive, pick two points and measure the average between them.
The straight line drawn through two points of a curve is called a secant, and its slope is the average rate of change of the curve across that stretch. Let us make that concrete on the curve in the box below.
f(x) = 0.5·x² − x + 2.5where f(x) is just the name for the curve’s height at input x.
Worked example
Take the two points where x is 3 and x is 5. The heights there are
f(3) = 0.5·9 − 3 + 2.5 = 4
f(5) = 0.5·25 − 5 + 2.5 = 10so between them the curve rose from 4 to 10, a rise of 6, over a run of 2.
average slope = (10 − 4) / (5 − 3) = 3That is what the box below shows on load. The base point starts at x = 3, the gap is 2, and the solid line through the two points has slope 3.00, exactly the number we just computed by hand. The dashed line and the second readout will be explained shortly. For now, drag the base point around and watch the average slope change as the stretch of curve under it changes.
The solid secant is the average slope across the gap. Shrink the gap and it rotates onto the dashed tangent, the derivative at the base.
4. Shrinking the Interval
An average across a stretch is still not what we set out to find. We wanted the steepness of the curve at a single point, the speedometer reading rather than the trip average. And a single point, on its own, gives us nothing to divide, since one point has no rise and no run. It looks like a dead end.
Here is the move everything else is built on. If the average across a stretch is the wrong answer because the stretch is too wide, then shrink the stretch. Keep the base point at x = 3 and pull the second point closer, computing the same rise over run every time. Each average is taken across a shorter piece of curve, so each is a better stand-in for the steepness right at the base.
Worked example, one smaller gap
Move the second point from x = 5 in to x = 4, a gap of 1.
f(4) = 0.5·16 − 4 + 2.5 = 6.5
average slope = (6.5 − 4) / (4 − 3) = 2.5 / 1 = 2.5The average fell from 3 to 2.5. The stretch from 3 to 5 climbed steeply at its far end, and pulling the second point in to 4 left the steepest part of it out of the measurement. Continue inward and the averages keep falling, which is the whole of the idea.
Working every row the same way gives this, and every one of them is a position of the gap slider in the box above.
| gap | second point | average slope |
|---|---|---|
| 2.00 | x = 5.00 | 3.00 |
| 1.00 | x = 4.00 | 2.50 |
| 0.50 | x = 3.50 | 2.25 |
| 0.10 | x = 3.10 | 2.05 |
| 0.02 | x = 3.02 | 2.01 |
Slide the gap down from 2.00 and the average-slope readout walks through these exact numbers.
The averages are not wandering. They are settling, and the smaller the gap the closer they settle. 3, then 2.5, then 2.25, then 2.05, then 2.01. Nothing here yet says what they settle on, or gives that value a name. What the table shows is only that they are heading somewhere, and that where they are heading does not depend on how we got there.
Check yourself
Questions on Sections 1 to 4
Question 1 of 5
A trip of 100 miles in 2 hours has a slope of 50 miles per hour, so the speedometer must have read 50 at some point along the way.
5. The Derivative
The value those averages close in on, 2 here, is the instantaneous rate of change of the curve at x = 3. That is what a derivative is, and it is worth saying plainly that you have already computed one. The name arrives after the idea rather than before it.
Writing the gap as h, the definition says to take the average slope across a gap of h and ask what value it approaches as h shrinks toward zero.
(f(x + h) − f(x)) / h, as h approaches 0Written the conventional way, with a prime mark for the derivative and lim for the approaching, that is
f'(x) = lim(h → 0) (f(x + h) − f(x)) / hThe picture of the same process is the two lines in the box above. While the second point slides in, the solid secant rotates, and it settles onto the dashed line, the tangent, the one straight line that grazes the curve at the base point and runs alongside it there. The secant measures an average and the tangent is what the averages become, so the slope of the tangent is the derivative. That is why the two readouts meet as the gap closes.
›About the limit
The definition says h approaches zero, not that h equals zero, and the distinction is the whole reason the notation exists. Setting h to zero outright gives 0 divided by 0, which is not a number, so the expression genuinely has no value there.
What it has instead is a value it gets arbitrarily close to. Name any tolerance you like, a thousandth, a millionth, and there is a gap small enough that every average slope from there inward sits within that tolerance of 2. That is what lim means, and it is a claim about every sufficiently small gap rather than about one impossible one.
Section 7 makes this concrete for our curve. The average slope across a gap of h works out to x + 0.5·h − 1 exactly, so the distance from x − 1 is 0.5·h, and choosing a small enough h makes that distance as small as anyone asks.
6. A Derivative at One Point Versus Every Point
What the shrinking-gap experiment found was one number, the slope at x = 3. Doing that again at x = 4, and again at x = 4.1, would be a miserable way to work, and it would never finish, because a curve has infinitely many points.
It matters because of what the slope is for. The walk in section 11 reads the slope where it stands, moves, and reads it again somewhere new, at x = 5, then at 3.8, then at 2.96, and none of those places was known before the walk set out. A slope found once at x = 3 answers none of those requests. What the walk needs is an instrument it can point at any x and read on the spot, not a reading taken in advance.
The remarkable thing is that the shrinking-gap calculation can be carried out with the gap left as the letter h and the base left as the letter x, which does every point at once. What comes out is not a number but a formula, a rule that returns the slope at whichever point you hand it. That is the next section, and it is ordinary algebra throughout.
The notation keeps the two apart. f’(3) is a number, the 2 that the shrinking gaps settled on. f’(x), with the x left in, is the rule itself, and f’(3) is what the rule says when handed 3. One derivation produces the rule, and every reading after that is a substitution into it.
7. Deriving the Slope Function
The recipe says to take the height at x + h, subtract the height at x, and divide by h. Here is that carried out on our curve, one operation per line, with nothing hidden.
| Expression | What changed |
|---|---|
| f(x) = 0.5·x² − x + 2.5 | The curve we are working on |
| f(x + h) = 0.5·(x + h)² − (x + h) + 2.5 | Substitute x + h wherever x appeared |
| = 0.5·x² + x·h + 0.5·h² − x − h + 2.5 | Expand the square and clear the brackets |
| f(x + h) − f(x) = x·h + 0.5·h² − h | Subtract the original height. The 0.5·x², the −x and the 2.5 appear in both and cancel |
| (f(x + h) − f(x)) / h = x + 0.5·h − 1 | Divide by the change in input. Every term loses one h |
| f'(x) = x − 1 | Let h approach zero, and the 0.5·h term dies away |
The second-to-last line says that the average slope differs from the derivative by half the gap. At a base point of three, the derivative is two.
average slope = x − 1 + h/2
at x = 3 and h = 1: 3 − 1 + 1/2 = 2.5
at x = 3 and h = 0.1: 3 − 1 + 0.1/2 = 2.05These are the values in section 4’s table. Letting the gap approach zero removes the extra term and leaves the derivative.
What is left is one clean formula for the slope at every point of the curve at once. Drag the base point anywhere in the box above and the derivative readout will be x − 1 to the last digit, because that is exactly what the server computes.
8. Reading What the Derivative Says
A derivative is not merely another formula to carry around. It describes the curve, and three readings cover most of what anyone needs from it. Take f’(x) = x − 1 and evaluate it in a few places.
| x | f'(x) | what the curve is doing there |
|---|---|---|
| 0 | −1 | falling |
| 1 | 0 | flat |
| 3 | 2 | rising, and twice as steeply as at x = 0 |
So the sign gives the direction, negative for falling and positive for rising. The magnitude gives the steepness, so a derivative of 2 is twice as steep as one of 1 regardless of which way either points. And zero marks a flat place, where the curve has stopped doing one and not yet begun the other.
The magnitude has a use beyond comparison. A rate multiplied by a run predicts a rise, as 50 miles per hour times 2 hours predicts the 100 miles of section 2, and a derivative is a rate, so it predicts how much the height will change over a short run from the point it was read at.
Worked example, predicting a small change
At x = 3 the derivative is 2. Step 0.02 to the right and the height should rise by about 2 times 0.02.
predicted rise = 2 × 0.02 = 0.04
actual rise = f(3.02) − f(3) = 4.0402 − 4 = 0.0402At x = 0 the derivative is −1, so the same step should lower the height by about 0.02.
predicted change = −1 × 0.02 = −0.02
actual change = f(0.02) − f(0) = 2.4802 − 2.5 = −0.0198Each prediction misses by two ten-thousandths, and the sign of each was right before any arithmetic was done. This is the reading the walk in section 11 relies on. It moves against the sign so that the height falls, and it moves further where the magnitude is larger.
Keep in mind
The reading is local. Over a longer run the slope changes along the way and the prediction drifts.
from x = 3 over a run of 0.5
predicted rise = 2 × 0.5 = 1.0
actual rise = f(3.5) − f(3) = 5.125 − 4 = 1.125The miss of 0.125 is the h/2 that section 7 finds in the average slope, which is 0.25 for this run, applied across the whole run of 0.5. A derivative describes the curve at the point it was taken and nearby, and says nothing about the far side of the drawing.
Those three readings are enough to find the bottom of a curve, which is what the rest of this primer does with them.
Check yourself
Questions on Sections 5 to 8
Question 1 of 5
Setting h to zero in (f(x + h) − f(x)) / h gives the derivative directly.
9. Flat Points and Minima
At an interior minimum of a differentiable curve, the derivative is zero. That gives us candidate locations to check. We still need to establish whether a flat point is a minimum, maximum, or neither.
Worked example
Set the derivative to zero and solve.
f'(x) = x − 1 = 0 → x = 1Then find the height there.
f(1) = 0.5·1 − 1 + 2.5 = 2The lowest point of this curve sits at (1, 2), found without looking at the drawing at all.
Keep in mind
A zero derivative marks any flat spot, and the bottom of a valley is not the only place a curve lies flat. The top of a hill is flat too.
What separates the two is the sign on either side. At a floor the curve falls in and rises out, so the derivative runs negative to positive. At a crest it rises in and falls out, so the derivative runs positive to negative. A zero derivative tells you the curve is flat there and nothing more, and you read the signs around it to know which kind of flat you have found.
10. Finding the Bottom by Walking
For this example, finding the point with zero slope takes one short equation.
f′(x) = 0
x − 1 = 0
x = 1Other functions need not be so cooperative. A model’s loss can depend on many parameters at once, and setting all its derivatives to zero may produce equations we cannot solve directly. That motivates taking repeated steps guided by the gradient.
So we keep the insight, that the bottom is where the slope is zero, and give up on jumping there in one algebraic step. Instead we walk, and we use the derivative the other way, not as an equation to solve but as a direction to follow.
Picture standing on a hillside in thick fog. You cannot see the valley floor, only the ground at your feet, but the slope underfoot still tells you which way is down. Stand where the slope is negative, the ground falling to your right, and downhill is to the right, so you want to increase x. Stand where the slope is positive and downhill is to the left, so you want to decrease x. In both cases you move against the sign of the slope.
That is what the rule says, and now it should read as inevitable rather than arbitrary.
x ← x − η · f'(x)The minus sign is the “against”. The η, a number you choose, is how boldly to act on what the slope told you, and it has a section of its own shortly.
11. One Complete Gradient-Descent Step
One update, worked all the way through, on the curve we have been using throughout. Start at x = 5 with η = 0.3.
Worked example
| quantity | value | where it came from |
|---|---|---|
| current location | x = 5 | chosen as a starting point |
| current height | f(5) = 10 | 0.5·25 − 5 + 2.5 |
| current slope | f'(5) = 4 | x − 1, at x = 5 |
| learning rate | η = 0.3 | chosen |
| movement | −0.3 × 4 = −1.2 | against the slope, scaled by η |
| new location | x = 5 − 1.2 = 3.8 | current location plus movement |
| new height | f(3.8) = 5.92 | 0.5·14.44 − 3.8 + 2.5 |
The height fell from 10 to 5.92, which is the whole point of the exercise, and the slope at the new location will be smaller than 4, so the next stride will be shorter.
Carrying on from there, the next few steps go like this.
| step | x | height | slope | movement |
|---|---|---|---|---|
| 0 | 5.0000 | 10.0000 | 4.0000 | −1.2000 |
| 1 | 3.8000 | 5.9200 | 2.8000 | −0.8400 |
| 2 | 2.9600 | 3.9208 | 1.9600 | −0.5880 |
| 3 | 2.3720 | 2.9412 | 1.3720 | −0.4116 |
| 4 | 1.9604 | 2.4612 | 0.9604 | −0.2881 |
| 5 | 1.6723 | 2.2260 | 0.6723 | −0.2017 |
The location approaches x = 1 and the height approaches 2. The slope and movement approach zero, so the strides shrink as the curve becomes flatter.
Each row is made from the one above it by the same three operations, reading the slope at the new location, scaling it by the rate, and moving against it. From the end of step 1,
slope at 3.8 = 3.8 − 1 = 2.8
movement = −0.3 × 2.8 = −0.84
new location = 3.8 − 0.84 = 2.96which is row 2, and every later row checks the same way.
Nothing tells the walk to slow down. It slows because the ground flattens, and the step is sized by the slope it reads.
Keep in mind
The walk never lands on the floor. The distance left after step 5 is 0.6723, and each further step removes only a part of what remains, so the location approaches x = 1 without reaching it. A walk like this is stopped rather than finished, either when a movement falls below a size you have decided is too small to matter, or when it has taken as many steps as you were willing to pay for. The second kind of stop is not an arrival, and a walk stopped that way can still be far from the bottom.
Check yourself
Questions on Sections 9 to 11
Question 1 of 5
A point where the derivative is zero is a minimum of the curve.
12. The Learning Rate
The one choice left in the walk is η, how far to move on each step. The slope gives a direction and a magnitude, and η decides how boldly to act on them. It is easier to see what it does than to be told, so start with the box below.
Click the curve to choose where the walk starts.
Computing the walk…
Click anywhere on the curve to choose a start and watch the walk come down. Each dot is one step, and the dashed line is the tangent at the start, the very line the earlier sections built. Now move the rate slider and four distinct behaviours appear.
| rate | what you see |
|---|---|
| 0.05 | creeps down, correct but wasting steps |
| 0.30 | glides down one wall and settles |
| 1.90 | crosses the bowl every step, zigzagging, still settling |
| 2.50 | each hop longer than the last, and the walk runs away |
The third case is the surprising one. It looks alarming and it is still converging, and the fourth looks similar for a step or two before it leaves. Something changes between 1.9 and 2.5, and for this particular bowl we can say exactly what.
›Why this happens
We know the derivative of this curve exactly, f’(x) = x − 1, so substitute it into the update rule.
x ← x − η·(x − 1)Subtract 1 from both sides, and the rule becomes a statement about the distance between where we stand and the floor at x = 1.
(x − 1) ← (1 − η) · (x − 1)Every step multiplies the distance from the bottom by the same factor, 1 − η, and the entire behaviour of the walk is in that one number. You can check it against the step table in section 11, where the distances from x = 1 run 4, 2.8, 1.96, 1.372, each exactly 0.7 of the one before it.
| η | factor 1 − η | what that does |
|---|---|---|
| 0.3 | 0.7 | each step closes 30% of the distance |
| 1.0 | 0.0 | one step lands exactly on the floor |
| 1.9 | −0.9 | crosses to the far side, yet closer than before |
| 2.0 | −1.0 | hops between two mirror points forever |
| 2.5 | −1.5 | grows every step, and the walk runs away |
So the sign of 1 − η says whether a step crosses the floor, and its magnitude says whether the distance shrinks. Below 2 the magnitude is under one and the walk converges however it looks on the way. At exactly 2 it is one, and the walk neither closes nor escapes. Above 2 it exceeds one and every hop is longer than the last.
The threshold sits at 2 for this bowl because of its particular steepness. A sharper curve turns unstable at a smaller η and a gentler one tolerates a larger, though the pattern, converge below some threshold and run away above it, is general.
That is the trade the learning rate sets. Too small wastes steps, too large diverges, and the workable range in between is found by exactly the kind of experiment the slider lets you run.
13. Local and Global Minima
Switch the box above to the two-valley curve, and the caution from section 9 becomes something you can watch. Start on the left of the central hill and the walk settles in the left valley. Start on the right and it settles in the right one. Same curve, same rule, different answer.
With sufficiently small steps, this walk stays in the valley where it starts. Its local slope gives it no reason to cross the hill to inspect the other valley. The bottom it reaches is a local minimum; the lowest point across the whole curve is the global minimum.
Keep in mind
Every model that fits itself by walking downhill inherits this. Where it starts can decide where it ends, which is why the same model trained twice can settle in two different places and report two different scores.
It is a real limitation rather than a fixable oversight, and the usual response is to run the walk more than once from different starts and keep the best result.
14. From One Setting to Many
Everything so far has had one adjustable value. A model has more, and the step from one to many is the last idea this primer owes you.
With one setting there is a loss L(θ), one derivative, and two directions to move, left or right. With two settings there is a loss L(θ₁, θ₂), and the picture becomes a surface rather than a line. There is no single slope on a surface, because the ground can tilt one way as you walk east and another as you walk north.
What there is instead is one slope per direction, found by asking how the loss changes as you vary one setting while holding the other still. Each of those is called a partial derivative.
Collect them and you have the gradient, written with a nabla.
∇L = ( ∂L/∂θ₁, ∂L/∂θ₂, …, ∂L/∂θₙ )The update rule then reads exactly as it did before, with the single slope replaced by the whole collection and the single value replaced by all of them at once.
θ ← θ − η·∇LIn a model
A model may have thousands or millions of adjustable parameters, one partial derivative each. The picture becomes impossible to draw well before that, and the principle does not change. Read how the loss responds to each setting, and move every setting in the direction that is expected to reduce it.
Everything you watched on the one-dimensional bowl happens there too. The strides shrink as the ground flattens, the rate can be too small or too hot, and the valley it settles in is a nearby one rather than necessarily the lowest.
Check yourself
Questions on Sections 12 to 14
Question 1 of 5
Every step of the walk multiplies the distance from the bottom by the same factor. What is it?
Try it with Botie
Build with Botie
Write and run Python