Lesson 7 of 7 · Math for AI: Linear Algebra & Calculus Essentials

Integrals: Accumulation, Area & the Continuous Side of Probability

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").

1. The integral is a sum of thin slices

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

∫ab f(x) dx

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:

00.511.5 22.53 x 059 f(x) = x² six rectangles: total area 6.875 true area under the curve: 9

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:

heights: 0 + 0.25 + 1 + 2.25 + 4 + 6.25 = 13.75
width: 0.5
area ≈ 13.75 × 0.5 = 6.875

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 nLeft edgesRight edgesMidpoints
66.875011.37508.9375
127.906210.15628.9844
1008.86549.13548.9998
1,0008.98659.01359.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.

Key Insight An integral is a continuous sum. Wherever a discrete method adds up values (a weighted average, the total of a probability table), the continuous version integrates. The shapes of the formulas match; the Σ becomes a ∫.

2. Antiderivatives and the fundamental theorem of calculus

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.

∫ab f(x) dx = F(b) − F(a) where F′ = f

Instead of adding a thousand rectangles, evaluate the antiderivative at the two ends and subtract. For the curve above:

F(x) = x³ / 3
F(3) = 27 / 3 = 9
F(0) = 0
∫03 x² dx = 9 − 0 = 9

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.

3. The few integrals you actually need

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
exexex is its own derivative
1/xln(x), for x > 0d/dx ln(x) = 1/x

Three worked definite integrals, each checked against a numeric sum in Python:

Power rule: ∫02 3x² dx = [x³]02 = 8 − 0 = 8
Exponential: ∫01 ex dx = e¹ − e⁰ = 2.71828 − 1 = 1.71828
1/x: ∫12 (1/x) dx = ln 2 − ln 1 = 0.69315 − 0 = 0.69315

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).

4. Probability densities: area is probability

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:

P(a ≤ X ≤ b) = ∫ab f(x) dx

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.

Worked example: request inter-arrival times

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:

f(t) = 2 e−2t for t ≥ 0

First, check it is a valid density. Its total area should be 1:

∫0∞ 2e−2t dt = [−e−2t]0∞
As t→∞, e−2t → 0, so the upper end gives 0.
At t=0, −e0 = −1.
0 − (−1) = 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:

F(t) = ∫0t 2e−2s ds = [−e−2s]0t = 1 − e−2t

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:

P(0.5 ≤ T ≤ 1.5) = F(1.5) − F(0.5)
= (1 − e−3) − (1 − e−1)
= e−1 − e−3
= 0.36788 − 0.04979
= 0.3181

A numeric Riemann sum of the density over [0.5, 1.5] in Python gives 0.31809, the same value to four decimals.

Key Insight The CDF is the integral of the density, and the density is the derivative of the CDF. That is the fundamental theorem again, and it is why the statistics course could move between "density" and "cumulative" without a new idea.

5. Expected value as an integral

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:

E[X] = ∫ x · f(x) dx (over the range where f is not zero)

Same idea: each possible value, weighted by how much probability sits near it, added up.

A uniform density

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:

E[X] = ∫04 x · (1/4) dx = (1/4) · [x²/2]04
= (1/4) · (16/2 − 0) = (1/4) · 8
= 2 seconds

The midpoint of the range, which is what your intuition says for a flat density.

The exponential density from section 4

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:

∫ t · λe−λt dt = [−t e−λt] + ∫ e−λt dt
From 0 to ∞: the bracket is 0 − 0 = 0 (the exponential beats t).
∫0∞ e−λt dt = 1/λ
E[T] = 1/λ = 1/2 = 0.5 seconds

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.

6. Normalizing constants: why softmax has a denominator

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:

e² = 7.3891 e¹ = 2.7183 e⁰ = 1.0000
sum (the normalizing constant) = 11.1073
 
probabilities: 7.3891/11.1073 = 0.6652
2.7183/11.1073 = 0.2447
1.0000/11.1073 = 0.0900

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:

∫−∞∞ e−x²/2 dx = √(2π) ≈ 2.5066

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.

7. Monte Carlo integration: average random samples

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:

∫01 g(x) dx ≈ (1/n) · [ g(u1) + g(u2) + … + g(un) ]

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 nEstimateError in this runTypical error, σ/√n
1000.729260.017570.0201
1,0000.738490.008330.0064
10,0000.744500.002320.0020
100,0000.747200.000380.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.

8. Numerical integration in one paragraph

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.

9. Where integrals hide in machine learning

You rarely type an integral sign in ML code. They are in the background of ideas you already use.

Marginalizing out a variable

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.

KL divergence

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.

The ELBO

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.

10. Why this matters for building AI systems

Why This Matters Integrals are the bridge between the discrete probability you met first and the continuous models that dominate modern AI.

You can see why training uses sampling

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.

How the whole math course fits together

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.

Recap

✅ Check Yourself

1. What is ∫03 x² dx, using the fundamental theorem of calculus?

6.875, the sum of the six left-edge rectangles
27, the value of x³ at 3
9, because the antiderivative x³/3 gives 27/3 − 0

2. A function f(x) is a valid probability density over all possible values. What must its total integral equal?

1, because the probability of all possible outcomes together is 1
The mean of the distribution
It depends on the units, and can be any positive number

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)?

f(1.5) − f(0.5), the difference in density heights
F(1.5) − F(0.5) = e−1 − e−3 ≈ 0.318
f(1) = 2e−2 ≈ 0.271, the density at the midpoint

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?

200, because the error falls in proportion to the samples
10,000, because the error falls like 1/n²
400, because the error falls like 1/√n, so halving it takes 4× the samples

5. In softmax, what job does the denominator (the sum of the exponentiated scores) do?

It is a normalizing constant that rescales the positive scores so they add up to 1
It makes the largest score bigger so the model is more confident
It is the derivative of the numerator, used in backpropagation