In P1.C1 you were given how far a car had travelled, and you found its speed. Now turn the question around. You are given the speedometer readings, second by second, and you want to know how far the car went. A tap pours water into a tank at a changing rate, and you want to know how much water is in the tank. A model assigns a probability density to a measurement, and you want the chance that the measurement falls between two values.
All three are the same job: add up a rate over a stretch to get a total. Doing this with thinner and thinner pieces gives the integral, the second great tool of calculus, and the one that probability is built on.
Adding up a rate
If the speed never changes, the answer is easy. At 3 m/s for 5 seconds the car goes m. On a graph with time across and speed up, this is a rectangle of height 3 and width 5, and 15 is its area. The unit fits too: (metres per second) seconds metres.
Now let the speed change. Take the toy car of P1.C1, with distance metres. Its speed is m/s: 0 at the start, 2 after one second, 6 after three. How far does it go in the first 3 seconds? We pretend we do not know and only know the speeds.
Cut the 3 seconds into three pieces of 1 second. Inside one piece the speed is not constant, but we can pick one speed for it and treat it as constant:
- speed at the start of each piece ( m/s): m;
- speed at the end of each piece ( m/s): m;
- speed in the middle of each piece ( m/s): m.
The car is speeding up, so the start-of-piece speeds are too low and the end-of-piece speeds are too high. The truth is between 6 and 12. The middle guess is 9, and from P1.C1 we know the true distance is m. Thinner pieces close in on it (the three right-hand columns are the total distance in metres):
| pieces | width | start | end | middle |
|---|---|---|---|---|
| 3 | 1 s | 6 | 12 | 9 |
| 6 | 0.5 s | 7.5 | 10.5 | 9 |
| 30 | 0.1 s | 8.7 | 9.3 | 9 |
(The middle guess is exactly 9 every time because this speed is a straight line: on each piece the too-low half cancels the too-high half. That is special to straight lines.)
The recipe has two steps. Cut the stretch into thin pieces, so the rate is nearly constant on each. Add up (rate on the piece) (width of the piece). The same recipe works for water into a tank (litres per minute minutes litres) or for any other rate.
Area under a curve
Each term in the recipe is the area of a rectangle: its height is the rate, and its width is the width of the piece. So the sum is the area of a row of rectangles, and as the rectangles get thinner, their tops follow the curve. That gives the key picture of this lesson:
The total accumulated from a rate is the area between the graph of the rate and the horizontal axis.
Whenever you see an area under a curve in machine learning, ask: what is the height a rate of, and what is the total? For a probability density, the height is probability per unit of , and the total is a probability.
Riemann sums
Now say it exactly, for a function on an interval from to . Cut the interval into strips of equal width
so and . A Riemann sum (named after the mathematician Bernhard Riemann) adds up over the strips. The sample point can be:
- the left end of each strip, ;
- the right end, ;
- the middle, for .
With the notation of P1.A3 (a sum with terms in each case):
The common factor can be pulled out of the sum (the first rule of P1.A3). The trapezoid rule joins the two ends of each strip by a slanted line, so each strip is a trapezoid, and its area is the width times the average of the two end heights. Adding them up gives exactly the average of the left and right sums: .
A first example, by hand
Let on with . Then and the strip ends are , where equals .
For the midpoint rule the heights are read at , where equals , , and , so .
Since is increasing, each left height is the smallest on its strip and each right height is the largest. So the true area lies between and (we will see it is ), and the midpoint sum is already close. More strips make this sharper:
| left | right | midpoint | |
|---|---|---|---|
| 4 | 0.21875 | 0.46875 | 0.328125 |
| 10 | 0.285 | 0.385 | 0.3325 |
| 100 | 0.32835 | 0.33835 | 0.333325 |
| 1000 | 0.33283 | 0.33383 | 0.33333 |
(The last row is rounded to 5 decimals.) All three columns head to .
The limit: the definite integral
For a continuous , the left, right, midpoint and trapezoid sums all approach the same number as (this is a theorem; this lesson checks it with numbers, not a proof). That number is the definite integral:
Here is what each symbol means:
- is a stretched letter S, for “sum”.
- and are the limits: where the interval starts and ends (the “limits of integration”, not the limit ).
- is the height of the curve at .
- stands for the width of a very thin strip, the of the sum after the limit. It also names the variable that runs from to . So “” reminds you of “height times strip width”.
As with in P1.C1, treat as one piece of notation for the limit of the sums. The is notation that reminds you of , the strip width in the sums. It is not a number that you can set to 0.01, divide by or cancel. The letter is a dummy variable, like the index of a sum in P1.A3: means exactly the same number. And the integral is a number, not a function of .
Checking exactly
For on the sums can be done exactly. The strip ends are and . The left sum is
using from P1.A3 with . In the same way , so , and the midpoint sum is . Every one of them tends to . (Check : , as in the table.) So
Things to try with the rectangles widget:
- Start with on , the left rule and : the sum is and the error is negative (the sum is too small). Switch to the right rule: too big. Midpoint: close. Slide up to 300 and watch all three sums meet the exact value .
- Choose speed 2t (on ). The midpoint and trapezoid rules give exactly 9 for every , as the table above said. The left and right sums are 9 minus and plus the same amount.
- Choose sin x on (exact area 2), then slide up to : strips below the axis turn red and hatched, and the sum falls to about 0. (Over a whole period the heights cancel by symmetry, so this particular case gives 0 for every and rule: a special case, not a sign that is large enough.) Signed area is the next section.
- Choose e⁻ˣ and slide up. The exact area from 0 to is , which gets closer to 1 but never reaches it. That is the area of a probability density, which later sections use.
- Choose x² − 1 and watch the last readout line. Which number settles down as grows, “error ” or “error ”, for the left rule? For the midpoint rule? (Left: error , near . Midpoint: error , near .)
Signed area: below the axis counts negative
If is negative, the rectangle “height” is negative, and its term is negative too. So the integral is a signed area:
Example: on . It is below the axis for , where the area is , and above it for , where the area is . So the integral is , which the widget shows. Another: , since the hump above the axis and the hump below it are equal, while the total shaded region has area .
This is the right behaviour for rates: if the car’s velocity is negative, it is going backwards, and the integral of velocity is displacement (net change of position), not total distance travelled. To get the total area between a curve and the axis, integrate instead.
Rules that follow from the sums (the same rules as for in P1.A3), for and continuous:
- (no width, no area);
- (walking the interval backwards makes every negative);
- (cut the interval at any between and );
- , and for a constant .
How fast do the sums converge?
The sums approach the integral, but at different speeds. For on we know the errors exactly from the formulas above. Here are the errors (sum minus exact) as doubles:
| left | midpoint | trapezoid | |
|---|---|---|---|
| 10 | |||
| 20 | |||
| 40 | |||
| 80 |
Doubling cuts the left error by about 2 and the midpoint and trapezoid errors by about 4. (The trapezoid errors are positive. The right error is nearly the left error with the sign flipped: .) In words: for a smooth function, the left and right rules have error of order , and the midpoint and trapezoid rules of order . To gain one more correct digit, the left rule needs ten times as many strips; the midpoint rule about times as many ().
Two cautions. First, “smooth” matters: these rates assume a function with continuous derivatives, not a corner or a jump inside the interval. Second, the rates are about the typical case, not a law for every function and interval: for on the left, right and trapezoid sums are all the same number (both end heights are 0), and their error is of order , not (the code cell below shows it). The Go-deeper box gives the rule that explains both.
Go deeper Where the error sizes come from
For a smooth and large , the errors are close to the following (sum minus exact; this is the leading term of the Euler–Maclaurin formula, stated here and checked with numbers, not proved):
For on : and , so at () the left error is about (true ), the midpoint , and the trapezoid , matching the table. The left and right errors depend on the change of across the interval: if (like on ) that term vanishes and the next one, of order , remains. The midpoint error is about half the trapezoid error and has the opposite sign, which is why combining them (Simpson’s rule) works so well; that rule is not taught here.
The fundamental theorem of calculus
Computing an integral as a limit of sums is slow. The shortcut connects this lesson to P1.C1, and it is one of the most important results in calculus.
Part 1: the area so far has slope
Fix a starting point and let the right-hand end move. The area collected from up to is a function of , the accumulation function:
(The variable inside is called because is already the upper limit.) Slide to the right and grows by a thin new strip. How fast?
A new strip of width starts at . If is small, hardly changes across it, so the strip is nearly a rectangle of height and width :
so
The left side is the difference quotient of P1.C1. As it tends to , and the right side is . For continuous this gives part 1 of the theorem:
Numbers, for and , where : at , with , and the quotient is , near . With it is . (Here comes from part 2, below; the sums confirm it.)
In words: the rate at which the area grows equals the height of the curve. Taller curve, faster growth. Where is negative, falls. Where crosses zero, is flat for an instant.
Things to try with the accumulation widget:
- With , drag from 0 to 2.5. While is negative (up to ), the area is negative and falls; at , where crosses zero, the tangent of is flat; afterwards rises. The readout “slope of ” matches at every position.
- Choose cos t and drag across : crosses zero, and has its peak there.
- Choose e⁻ᵗ: stays positive, so always rises, but more and more slowly, and levels off near 1.
- Compare “” with “ from 2000 thin strips”: the formula and the thin-strip sum agree.
Part 2: integrals from antiderivatives
A function is an antiderivative of if . Part 1 says is one antiderivative of . Suppose is another. Two functions with the same derivative on an interval differ only by a constant (a fact we use without proof here), so . Then . This is part 2:
where . It is usually written . The condition is that is continuous on and at every point of .
Check: has (the power rule of P1.C2), so , which the sums gave with a lot more work. For the toy car, has , so m.
Read part 2 as: the integral of a rate is the total change. The car’s speed is the derivative of its distance, so adding up the speeds gives the change in distance, . This is the accumulation idea, and the shortcut at once. Differentiation and integration undo each other: part 1 says differentiating an integral returns the function, and part 2 says integrating a derivative returns the change.
Part 1 is useful even when you cannot find a formula. For there is no simple , yet part 1 tells you at once that .
Antiderivatives: the rules backwards
Every derivative rule of P1.C2 gives an integral rule when read backwards. Always check an answer by differentiating it.
- Powers. For : . The derivative of the right side is . Examples: , , (on either side of 0), (for ).
- The exception, . The formula would divide by . A different function does the job: for (P1.C2), and for the derivative of is also (a central difference at gives ; the chain rule of P1.C3 shows why). So on each side of 0 separately. The integral is valid when (or with ), and not when lies between and : there is not defined at 0 and its area is infinite on each side.
- Exponentials. , and for a constant , . Check by the limit of P1.C1: , because with . For example , the curve of the widget.
- Sine. . This uses , a fact from a table of derivatives that is not derived in this course; the widget’s sums for agree with .
- Sums and multiples. and . For example .
The constant . Adding any constant to an antiderivative gives another antiderivative, since constants have derivative 0. writes “all of them” at once, and is called the indefinite integral (a family of functions). In a definite integral cancels: . So you may take there.
Not every function has a closed-form antiderivative. The integral of cannot be written with powers, exponentials, logarithms and the other functions of this course (this has been proved, not just failed to be found). Its definite integrals still exist as numbers and can be computed by sums. Techniques for finding harder antiderivatives, such as substitution (the chain rule of P1.C3 read backwards) and integration by parts, are not part of this lesson; a computer does them, and ML rarely needs them by hand.
When there is no formula: numerical integration
Most integrals in ML have no antiderivative you can write down, or involve data. Then we use Riemann sums directly. The sum is simply a loop, and the rules differ in cost and accuracy:
- Midpoint and trapezoid rules are better than left and right for smooth functions (error of order ), at about the same cost (the trapezoid rule uses function values, since neighbouring strips share an end).
- With measured points only (for example a list of values at given values) the trapezoid rule is the natural choice: NumPy’s
numpy.trapezoid(y, x)computes it. Newer NumPy versions have the nametrapezoidand deprecate the older namenumpy.trapz; NumPy 2.2.1, used to check this lesson, still has both and warns whentrapzis used, and a deprecated name may be removed in a later version. The code cells here use plain Python so they run in your browser without NumPy. - Libraries also have adaptive routines (SciPy’s
scipy.integrate.quadis one) that choose the strips for you. - A grid of points per axis costs evaluations in dimensions, which is hopeless for large . Averaging over random points instead (Monte Carlo, P1.D9) is how high-dimensional integrals are estimated in ML.
Going to infinity: improper integrals
A density for a waiting time runs from 0 to . An integral over an unbounded range is defined as a limit:
when this limit is a finite number (we say the integral converges). For : , which is for . It tends to 1, so
The tail does shrink fast: beyond the area is . An integral over the whole line is split at any point, , and both halves must converge.
A height that tends to 0 is not enough. Compare and on . The first has area , which tends to 1. The second has area , which keeps growing: at , at , at . So , but does not converge, though too.
Why probability needs integrals
A continuous quantity, such as a waiting time or a pixel intensity, can take any value in a range, so the probability of one exact value is 0 (there are too many values to share the total). Instead we describe it with a probability density and give the probability of an interval as an area:
(P1.D2 is the lesson about random variables and densities; this lesson gives the integral part.) The height is probability per unit of , not a probability. It can be above 1: a density that is 2 on an interval of width has area .
Uniform density. All values in are equally likely: there and 0 elsewhere. The total area is . The probability of is .
Exponential density. For a waiting time, for (and 0 for ). The total area is 1 (the improper integral above). Probabilities are areas: , and ; the three add to 1, as three areas that tile the whole should.
The CDF is an accumulation function. The cumulative distribution function (written so it is not confused with an antiderivative ) is the area so far, so by part 1 of the fundamental theorem . For the exponential density, (for ) and . The sigmoid of P1.A5 is also a CDF: is the CDF of the standard logistic distribution. Its slope (P1.C1, P1.C2) is the bell-shaped logistic density, with total area by part 2, and . (P1.D2 develops CDFs.)
Expected value. The mean of discrete values is a weighted sum . For a density the sum becomes an integral, : each value is weighted by the probability of landing in a thin strip around it. For the uniform density on : , the middle of the range. For it is 1 as well (finding it needs integration by parts, not taught here; a fine numerical sum agrees with 1 to eight decimal places, which is a check, not a proof). P1.D4 covers expectation properly.
Normalising constants. The Gaussian bell has total area The function has no antiderivative made from elementary functions; the value is a known result whose proof (not given here) uses two dimensions, and the sums below agree. To make the total area exactly 1, the standard normal density divides by it: , whose peak height is (P1.D3). Any “unnormalised” density becomes a real one when you divide it by its total area, which is an integral.
Area under the ROC curve (AUC). A classifier’s ROC curve plots the true-positive rate against the false-positive rate as the decision threshold moves; AUC is the area under it, 1 for a perfect classifier and for the diagonal, which is random guessing (P3.A9). A ROC curve is a list of points, so its area is found with the trapezoid rule (scikit-learn’s auc function is documented as using it). For the points the three trapezoids have areas , and the AUC is .
The average value of a function
The average value of on is
It is the height of the rectangle on with the same area as the region under the curve. Why this deserves the name: divide a Riemann sum by . Since ,
the ordinary mean of evenly spaced heights. The average value is what those means approach as . For on : , so . The mean of the three heights at is , and with 100 midpoints it is .
For the toy car, m/s is the average speed: , the average rate of change of P1.C1. In general the average value of a derivative is .
The link to machine learning. A model’s expected loss over a distribution of inputs, with density , is an integral , a weighted average of the loss. The loss averaged over training examples is : the same shape of formula, with the data points playing the part of the sample points. This works when the examples are independent draws from : the weighting by then happens by itself, because points land where is large. The data average estimates the expected loss, and on average gets closer as grows (the law of large numbers, P1.D8; sampling and Monte Carlo, P1.D9). That is why minimising the training loss is a sensible stand-in for minimising the loss on the whole distribution.
Integrals in three depths
Intuition
Cut a stretch into thin pieces, find how much accumulates on each piece (rate times width), and add. Thinner pieces give a better answer, and in the limit the answer is exact: the area under the rate curve. The slope of “the area so far” is the height of the curve, so finding a total is the reverse of finding a rate. In probability, the area under a density over an interval is the chance of that interval.
Math
Signed area; linearity; additivity over intervals. Fundamental theorem: ; and when . Antiderivatives: (), , (). Error orders: left and right , midpoint and trapezoid for smooth . Density: , , , . Average value .
Code
def riemann(f, a, b, n, rule="midpoint"):
dx = (b - a) / n
xs = [a + (i + {"left": 0, "right": 1, "midpoint": 0.5}[rule]) * dx for i in range(n)]
return sum(f(x) for x in xs) * dx
riemann(lambda x: x * x, 0, 1, 1000) # about 0.33333With NumPy, for measured points, the trapezoid rule is one call:
import numpy as np
x = np.linspace(0, np.pi, 101)
np.trapezoid(np.sin(x), x) # about 2 (newer NumPy versions; older ones call it np.trapz)Try it: errors of Riemann sums, and probabilities as areas
The first cell builds the four rules and prints their errors as doubles. Predict the pattern before you run it: which columns drop by a factor of 2, and which by 4? The second cell computes the areas of the lesson’s densities and the AUC example.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: change f to math.exp and the interval to (exact value ). Which rule is closest at , and is the sum above or below the exact value for the left rule?
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: the uniform density on is . Use midpoint to compute and compare it with 1.
Common mistakes
Check your understanding
Estimate with the left rule and 4 strips. You get , below the true value . Why is the left sum too small here?
On a rising curve the left end is the lowest point of each strip, so each rectangle sits under the curve. For a falling curve the left end is the highest point and the left sum would be too big, so the rule does not always underestimate. Using wider strips than 0 is not the cause; it only affects how large the error is. A strip’s area is height times width, not a quotient.
What is ?
The part of the curve above the axis on has area and the part below on counts as , so the signed total is . The number is the total area of the shaded region (counting both parts as positive), and is only the first hump.
Use an antiderivative to find .
An antiderivative is , and . The value comes from wrongly using , and from using (the derivative, not an antiderivative). The value is alone, forgetting to subtract .
A random quantity has the density for and elsewhere. Which statement is right?
The total area is , so it is a valid density. A density is probability per unit of and can exceed 1; what must not exceed 1 is a probability, which is an area. The area up to is , so a probability of 2 is impossible, and the total area is 1, not .
Why can the rule not be used for ?
The power rule of P1.C2 holds for too, so is the power . It is the antiderivative formula that breaks at , because of the division by 0, and the logarithm fills the gap: has derivative for . So an antiderivative exists, and is allowed as always.
Exercises
- Let on with strips. Find the left, right and midpoint sums, and compare them with the exact value.
Show answer
. Left: . Right: . Midpoint, with heights at : . The exact value is , between the left and right sums, with the midpoint closest. - Evaluate and .
Show answer
, so the first is . For the second, , so . - Evaluate . What is the area above the axis, the area below, and the total area between the line and the axis?
Show answer
. The integral is . The line is below the axis on , with area (integral ), and above it on , with area . So the integral is , and the total area between line and axis is . - Find , and explain why the same method does not work for .
Show answer
. For , the interval contains 0, where is not defined and its height is unbounded. Writing would be wrong: the area on each side of 0 is infinite, so the integral is not a finite number. - Find without finding the integral.
Show answer
By part 1 of the fundamental theorem, it is . - The function on (and 0 elsewhere) is a density. Check that its total area is 1, find and .
Show answer
. . . - Find the average value of on .
Show answer
. - A tap runs at litres per minute for the first 3 minutes. How much water has flowed? Which part of the lesson does this match?
Show answer
litres: the toy car’s speed again, with litres per minute minutes litres. The total is the area under the rate curve. - A ROC curve passes through . Find the AUC with the trapezoid rule.
Show answer
. - Does converge? If so, to what?
Show answer
. It converges to .
Next: P1.C10 shows how a computer finds the derivatives of whole programs exactly. Integrals return in Module 1D, where densities and the areas of this lesson give probability its continuous half.