Derivatives tell you the rate of change at one instant. Integrals run the other way: they add up infinitely many tiny pieces. Every continuous probability, every expected value, and every softmax denominator is one.
M4 was about derivatives: how an output moves when an input is nudged. This lesson is the reverse question. If you know the rate at every moment, how much has piled up? If you know how dense the probability is at every point, how likely is a whole range? The tool is the integral, and it is the one piece of calculus that the statistics course leans on without ever teaching you to compute. Here you meet it directly, then use it to finish the picture started in the statistics course, Lesson 12 ("Random Variables") and Lesson 13 ("Continuous Distributions").
Suppose a team logs how fast tokens stream out of a model: 40 tokens per second for 2 seconds, then 60 tokens per second for 3 seconds. The total is just rate × time, added up: 40×2 + 60×3 = 80 + 180 = 260 tokens. On a graph of rate against time, each term is the area of a rectangle, and the total is the total area.
Now let the rate change smoothly instead of in steps. You can still chop the time axis into slices, treat the rate as constant inside each slice, and add up rectangles. Thinner slices fit the curve better. The value the sums approach as the slices shrink to nothing is the definite integral, written
Read it as: "add up f(x) × (a tiny width dx) for every x from a to b." The ∫ sign is a stretched S for "sum", f(x) is the height of the curve, and dx is the width of a slice. The result is the signed area between the curve and the x-axis, with area below the axis counted as negative.
Take the curve f(x) = x² on the interval from 0 to 3. Here are six left-edge rectangles, each 0.5 wide:
Each rectangle uses the curve's height at its left edge, so on a rising curve every one falls short. The gap is the sliver between the rectangle's top and the curve.
The arithmetic, with the heights read off f(x) = x² at x = 0, 0.5, 1, 1.5, 2, 2.5:
That undershoots. Switch to the right edge of each slice and it overshoots. Use the midpoint and it lands very close. Shrink the slices and all three converge on the same number. This is a Riemann sum, and these values were computed in Python with n equal slices over [0, 3]:
| Slices n | Left edges | Right edges | Midpoints |
|---|---|---|---|
| 6 | 6.8750 | 11.3750 | 8.9375 |
| 12 | 7.9062 | 10.1562 | 8.9844 |
| 100 | 8.8654 | 9.1354 | 8.9998 |
| 1,000 | 8.9865 | 9.0135 | 9.0000 |
All three columns squeeze toward 9. That limit is ∫03 x² dx = 9. The next section shows how to skip the sum when the function is simple.
In M4 you took a function and found its derivative. An antiderivative of f is a function F whose derivative is f: F′(x) = f(x). For f(x) = x², try F(x) = x³/3. Its derivative, by the power rule from M4, is 3x²/3 = x². It works. (Add any constant to F and the derivative is unchanged, which is why antiderivatives are only defined up to a constant. That constant cancels below.)
The fundamental theorem of calculus connects the two ideas from this lesson: the area-sum and the antiderivative.
Instead of adding a thousand rectangles, evaluate the antiderivative at the two ends and subtract. For the curve above:
That matches the Riemann table. The theorem also says the two operations undo each other. Differentiate the running total of f and you get f back, and integrate a derivative and you get the net change. Derivative and integral are inverse operations, the way multiplication and division are.
You will rarely integrate by hand in AI work. When you do, it is one of three forms, each a derivative rule from M4 read backwards.
| Integrand f(x) | Antiderivative F(x) | Because |
|---|---|---|
| xn (for n ≠ −1) | xn+1 / (n+1) | the power rule, reversed |
| ex | ex | ex is its own derivative |
| 1/x | ln(x), for x > 0 | d/dx ln(x) = 1/x |
Three worked definite integrals, each checked against a numeric sum in Python:
One variation matters in this lesson: when the exponent has a constant inside, as in e−λx, the antiderivative picks up a factor of 1/(−λ). Check by differentiating: d/dx [−e−λx/λ] = −(−λ)e−λx/λ = e−λx. The chain rule is doing the work. Anything harder than this goes to a library or to a Monte Carlo estimate (section 7).
The statistics course, Lesson 13 ("Continuous Distributions") introduced a quantity that can take any value in a range, such as the time between two requests arriving at a server. For a continuous quantity, the chance of landing on one exact value, like exactly 0.7312… seconds, is zero. There are infinitely many possible values. So instead you describe the probability density function (pdf) f(x), and probability lives in areas:
The density at a point can be bigger than 1; it is a height, not a probability. What must hold is that the total area is 1, because something has to happen: ∫−∞∞ f(x) dx = 1. This is the continuous version of "the probabilities in the table sum to 1" from the statistics course, Lesson 3.
Say a team models the gap T (in seconds) between two requests hitting an inference endpoint with an exponential density at rate λ = 2 requests per second:
First, check it is a valid density. Its total area should be 1:
Now integrate the density from 0 up to t to get the cumulative distribution function (CDF), the probability that the gap is at most t:
From the CDF, any range is a subtraction, just like the fundamental theorem says. The chance the next request arrives between 0.5 s and 1.5 s after the last:
A numeric Riemann sum of the density over [0.5, 1.5] in Python gives 0.31809, the same value to four decimals.
In the statistics course, Lesson 12 ("Random Variables"), the expected value of a discrete random variable was a weighted average: each value times its probability, added up, E[X] = Σ x · P(x). For a continuous variable, the probabilities become a density and the sum becomes an integral:
Same idea: each possible value, weighted by how much probability sits near it, added up.
Say a job's start delay is equally likely to be anywhere from 0 to 4 seconds. The density is flat: f(x) = 1/4 on [0, 4]. First confirm the area: 4 × 1/4 = 1. Then:
The midpoint of the range, which is what your intuition says for a flat density.
The mean gap between requests is E[T] = ∫0∞ t · 2e−2t dt. This one needs a trick called integration by parts, which is the product rule for derivatives run backwards. The pieces:
This matches intuition: if requests arrive at 2 per second, the average gap is half a second. A numeric sum in Python returns 0.5000. For the uniform, it returns 2.0000.
Often you know how relative likelihoods compare before you know the actual probabilities. An unnormalized score or density is positive, but it does not add up (or integrate) to 1. The fix is always the same: divide by the total. That total is the normalizing constant.
Discrete case: a model produces three raw scores (logits) for next-token candidates: 2, 1, 0. Exponentiate to make them positive, then divide by the sum:
Those add to 1 (to rounding). The denominator in softmax is exactly this normalizing constant, the same idea as the "evidence" term in Bayes' Theorem in the statistics course, Lesson 3.
Continuous case: the bell-shaped function e−x²/2 is positive but its area is not 1. Its total area is a famous result, the Gaussian integral, which is stated here, not derived:
Divide by 2.5066 and you get the standard normal density, with 1/√(2π) out front. That constant is the reason the Gaussian formula looks the way it does. A numeric sum in Python confirms 2.5066.
When the antiderivative does not exist in closed form, or the integral has many dimensions, you can estimate it by randomness. The idea comes straight from the expected-value section: an integral over [0, 1] of g(x) is the same thing as E[g(U)] when U is uniform on [0, 1]. So draw n random points u1, …, un, evaluate g at each, and average:
Test it on g(x) = e−x² over [0, 1], which has no elementary antiderivative. A fine numeric sum gives the reference value 0.746824. Here is a Monte Carlo run in pure Python with a fixed random seed:
| Samples n | Estimate | Error in this run | Typical error, σ/√n |
|---|---|---|---|
| 100 | 0.72926 | 0.01757 | 0.0201 |
| 1,000 | 0.73849 | 0.00833 | 0.0064 |
| 10,000 | 0.74450 | 0.00232 | 0.0020 |
| 100,000 | 0.74720 | 0.00038 | 0.00064 |
The last column is the standard deviation of g(U), which is σ ≈ 0.2010 (also computed in Python), divided by √n. Averaging the squared error over 200 repeated runs gave typical errors of 0.0195, 0.0060, 0.0020 and 0.00064 for the four sample sizes, close to the formula.
The pattern is the central limit theorem at work. The estimate is a sample mean, so from the statistics course, Lesson 5 ("From Sample to Population: Estimation & the Central Limit Theorem"), its spread shrinks like 1/√n. To cut the error in half you need 4× the samples; for 10× better, 100×. The payoff is that this rate does not depend on how many dimensions the integral has, and that is why Monte Carlo is the standard tool when grid-based sums would be impossible.
For a smooth integral in one or two dimensions, a grid method is faster than random sampling. The trapezoid rule connects neighbouring points with straight lines and adds up the trapezoids: h × (half the first height + all the middle heights + half the last height), where h is the slice width. On the same integral of e−x² over [0, 1], 4 slices give 0.74298 (error 0.0038) and 8 slices give 0.74587 (error 0.00096). Doubling the slices cut the error by about 4×, so it shrinks like 1/n², much faster than Monte Carlo's 1/√n in one dimension. The trade flips as the number of dimensions grows, where grids need exponentially many points and random sampling does not.
You rarely type an integral sign in ML code. They are in the background of ideas you already use.
If a model has a hidden variable z you do not observe, the probability of what you do observe is P(x) = ∫ P(x | z) P(z) dz: sum over every possible z. For many models this integral cannot be computed exactly.
The statistics course, Lesson 7 covers it with sums. For continuous distributions it is an integral: KL(p ‖ q) = ∫ p(x) ln(p(x)/q(x)) dx.
Variational methods work around the hard marginalization integral by optimizing a lower bound on its logarithm, called the ELBO, which is itself an expectation (an integral) that is estimated with Monte Carlo samples.
The honest summary: the mathematics is integrals, and the practice is almost always sampling and averaging, because the integrals are too hard to solve. If you understand sections 5 and 7, you understand what that code is approximating.
A minibatch gradient is a Monte Carlo estimate of an expectation. Its noise follows the 1/√n law from section 7, which is why bigger batches help with diminishing returns: 4× the batch for half the noise.
Seven lessons, one pipeline. Linear algebra (M1–M3) gives the objects: embeddings are vectors, layers are matrix multiplications. Calculus (M4–M7) gives the learning signal, derivatives and gradients flowing back through the layers, plus (this lesson) the expectations and normalizers on the probability side. These come together in the statistics course, Lesson 8 ("The Statistics Behind Training a Model"): embeddings go through layers, a loss measures the error, gradients flow back, and training updates the weights.
1. What is ∫03 x² dx, using the fundamental theorem of calculus?
2. A function f(x) is a valid probability density over all possible values. What must its total integral equal?
3. For the density f(t) = 2e−2t, the CDF is F(t) = 1 − e−2t. How do you get P(0.5 ≤ T ≤ 1.5)?
4. A Monte Carlo estimate of an integral has a typical error of 0.02 with 100 samples. Roughly how many samples do you need to bring it to 0.01?
5. In softmax, what job does the denominator (the sum of the exponentiated scores) do?