22.6 Integral Calculus

Earlier chapters used continuous random variables without asking how their probabilities are computed. We described a normal distribution by its density (Section 2.1.3), wrote an expected loss as an average over that density, and treated both as given. In this section we ask how to add up a quantity that is spread continuously over an interval.

The standard normal distribution, the familiar bell curve, shows why continuous summation requires care. A standard normal random variable ZZ has density p(z)=e−z2/2/2πp(z)=e^{-z^2/2}/\sqrt{2\pi}. At z=0z=0 the curve reaches height p(0)≈0.40p(0)\approx 0.40, yet the probability of landing on zero is P(Z=0)=0P(Z=0)=0, and the same is true for every other single point. Intervals, on the other hand, do carry probability: P(−1≤Z≤1)≈0.68P(-1\le Z\le 1)\approx 0.68. Geometrically, that number is the area under pp between −1-1 and 11, and 1/2π1/\sqrt{2\pi} is the constant that makes the total area under the curve equal to 11. Where does 2π\sqrt{2\pi} come from, and how do we compute 0.680.68?

These questions reach well beyond the bell curve. Every probability and every expected loss over a continuous variable is an area of this kind. Training a model through random sampling, as variational autoencoders and policy-gradient methods do, also requires differentiating such an area with respect to a model parameter.

Our strategy is simple: cut the area into thin slices, add their areas, and let the slices shrink to zero. The limit is the integral. The fundamental theorem of calculus then replaces this infinite addition with the reverse of differentiation, which settles most integrals in a single line. It does not settle the bell curve, whose normalizing constant 2π\sqrt{2\pi} requires a detour through two dimensions. Three results anchor the section: the fundamental theorem (22.6.3), the multivariable change-of-variables formula (22.6.11), and the Gaussian integral (22.6.13). If you already have first-year calculus at hand, you can skim through to Section 22.6.2.2. Differentiating an integral with respect to a parameter builds on all of these tools and has a section of its own in Section 22.7. We leave out measure theory and the Lebesgue integral, pointing interested readers to Section 22.8.

22.6.1 The Definite Integral#

22.6.1.1 Riemann Sums#

A probability density gives probability per unit length, so over a short interval of width ϵ\epsilon the probability is approximately density times width. Over a longer interval, we cut it into thin slices, multiply height by width on each slice, and add the results. Nothing in this idea is specific to densities: the same recipe works for any function.

Let us start with a case we can work out by hand. Take f(x)=x2f(x)=x^2 on [0,1][0,1] and divide the interval into NN slices of equal width ϵ=1/N\epsilon=1/N. On the ii-th slice [i/N,(i+1)/N][i/N,(i+1)/N], we approximate the area by a rectangle whose height is the value of ff at the left endpoint, (i/N)2(i/N)^2. Adding all NN rectangles gives

∑i=0N−11N(iN)2=1N3∑i=0N−1i2=(N−1)N(2N−1)6N3=13−12N+16N2,\sum_{i=0}^{N-1}\frac1N\Bigl(\frac iN\Bigr)^2 =\frac{1}{N^3}\sum_{i=0}^{N-1}i^2 =\frac{(N-1)N(2N-1)}{6N^3} =\frac13-\frac1{2N}+\frac1{6N^2},

where the middle step uses the classical identity ∑i=0N−1i2=(N−1)N(2N−1)/6\sum_{i=0}^{N-1}i^2=(N-1)N(2N-1)/6. As NN grows, the rectangle sums converge to 13\tfrac13, missing the limit by roughly 12N\tfrac1{2N}, an error of first order in the slice width ϵ\epsilon.

The helper function left_sum implements this left-endpoint rule for any function ff: divide [a,b][a,b] into slices of width ϵ\epsilon and evaluate ff at the left end of each slice, as shown in Figure 22.6.1. We will use left_sum for every grid sum in this section, starting with a quick check on x2x^2.

def left_sum(f, a, b, eps):
    """Left-endpoint Riemann sum of f on [a, b] with slices of width eps."""
    x = a + eps * np.arange(round((b - a) / eps))   # left ends of the slices
    return float(np.sum(eps * f(x)))

for N in [10, 100, 1000]:
    print(f'N={N:<5} left sum={left_sum(lambda x: x**2, 0, 1, 1 / N):.6f}  '
          f'formula={1/3 - 1/(2*N) + 1/(6*N**2):.6f}')
N=10    left sum=0.285000  formula=0.285000
N=100   left sum=0.328350  formula=0.328350
N=1000  left sum=0.332834  formula=0.332834

The numerical sums match the closed-form formula to every printed digit.

The definition. Nothing in this construction requires equal slice widths or left endpoints. More generally, a partition P:a=x0<x1<⋯<xN=bP:a=x_0\lt x_1\lt \cdots\lt x_N=b cuts [a,b][a,b] into subintervals, a tag ξi∈[xi−1,xi]\xi_i\in[x_{i-1},x_i] picks one sample point inside each slice, and the mesh ∥P∥=max⁡i(xi−xi−1)\|P\|=\max_i(x_i-x_{i-1}) measures the width of the widest slice. A bounded function ff is Riemann integrable on [a,b][a,b] if there is a single number II that every tagged sum approaches as the mesh shrinks to zero, regardless of how the tags are chosen:

∫abf(x) dx=I=lim⁡∥P∥→0∑i=1Nf(ξi)(xi−xi−1).(22.6.1)\int_a^b f(x)\,dx = I = \lim_{\|P\|\to0}\sum_{i=1}^N f(\xi_i)(x_i-x_{i-1}). \tag{22.6.1}

In short, the definite integral is the common limit of the slice sums as the slices become arbitrarily thin. Our hand calculation above establishes ∫01x2 dx=13\int_0^1x^2\,dx=\tfrac13. Every continuous function on [a,b][a,b] is Riemann integrable, and so is every bounded function with finitely many jump discontinuities (Rudin, 1976). Some pathological bounded functions, such as the indicator of the rational numbers, fail to have a Riemann integral; the Lebesgue integral (Section 22.8) extends integration to them while agreeing with the Riemann integral whenever the latter exists.

Two elementary properties follow straight from the definition and will power the proofs below. First, the integral is monotone: if f≤gf\le g everywhere on [a,b][a,b], then every tagged sum of ff is no larger than the corresponding tagged sum of gg, and taking limits preserves the inequality, giving ∫abf dx≤∫abg dx\int_a^b f\,dx\le\int_a^b g\,dx. Second, it is additive over subintervals: for any a≤b≤ca\le b\le c, ∫acf dx=∫abf dx+∫bcf dx\int_a^c f\,dx=\int_a^b f\,dx+\int_b^c f\,dx, because any partition that includes the point bb splits cleanly into a partition of [a,b][a,b] and a partition of [b,c][b,c].

The running example. Until we reach the Gaussian integral, we will carry one concrete example through the section:

∫02x1+x2 dx=12log⁡5≈0.80472.\int_0^2\frac{x}{1+x^2}\,dx=\tfrac12\log5\approx 0.80472.

We will see why its value is 12log⁡5\tfrac12\log5 once we establish the evaluation rule (22.6.4). Figure 22.6.1 illustrates left-endpoint rectangles under this curve at three slice widths.

Figure 22.6.1:

Left-endpoint rectangles under f(x)=x/(1+x2)f(x)=x/(1+x^2) on [0,2][0,2] for slice widths ϵ=0.5\epsilon=0.5, 0.20.2, and 0.050.05. Each slice takes the height of ff at its left endpoint, and the rectangle sums approach the area 12log⁡5\tfrac12\log 5 as ϵ→0\epsilon\to0.

How quickly do the left sums converge to 12log⁡5\tfrac12\log5? For x2x^2 on [0,1][0,1] the error was 12N=ϵ2\tfrac1{2N}=\tfrac\epsilon2. If first-order convergence is typical, making the slices ten times thinner should reduce the error by a factor of ten. Let us check by printing the error alongside 0.2 ϵ0.2\,\epsilon.

f = lambda x: x / (1 + x**2)
truth = math.log(5) / 2
for eps in [1e-1, 1e-2, 1e-3, 1e-4]:
    s = left_sum(f, 0, 2, eps)
    print(f'eps={eps:.0e}  sum={s:.6f}  truth-sum={truth - s:.2e}  '
          f'0.2*eps={0.2 * eps:.0e}')
print(f'truth = (1/2) log 5 = {truth:.6f}')
eps=1e-01  sum=0.783785  truth-sum=2.09e-02  0.2*eps=2e-02
eps=1e-02  sum=0.802710  truth-sum=2.01e-03  0.2*eps=2e-03
eps=1e-03  sum=0.804519  truth-sum=2.00e-04  0.2*eps=2e-04
eps=1e-04  sum=0.804699  truth-sum=2.00e-05  0.2*eps=2e-05
truth = (1/2) log 5 = 0.804719

Each time ϵ\epsilon shrinks by a factor of ten, the error shrinks by ten as well, and every sum sits below the true value. The constant 0.20.2 happens to be half of f(2)−f(0)=0.4f(2)-f(0)=0.4. This is no coincidence, and we will derive the formula behind it as soon as the fundamental theorem is in place.

22.6.1.2 Signed Area#

Rectangles below the horizontal axis have negative height f(ξi)<0f(\xi_i)\lt 0 and enter the Riemann sum with a minus sign. The integral therefore measures signed area: regions where f<0f\lt 0 contribute negatively, as in ∫01(−1) dx=−1\int_0^1(-1)\,dx=-1. By convention, integrating from right to left also negates the result, ∫baf dx=−∫abf dx\int_b^a f\,dx=-\int_a^b f\,dx. This convention ensures that additivity holds regardless of how aa, bb, and cc are ordered. Figure 22.6.2 illustrates both conventions on a single curve.

Figure 22.6.2:

Signed area. Lobes above the axis count positively and the lobe below counts negatively, so ∫abf\int_a^b f totals the shaded regions with their signs; reversing the limits traverses the same area from right to left and negates the total.

22.6.2 The Fundamental Theorem#

22.6.2.1 The Theorem#

Adding slices gave 13\tfrac13 for x2x^2 only because ∑i2\sum i^2 happens to have a closed form. For our running example, the left sum is ∑iϵ⋅iϵ/(1+i2ϵ2)\sum_i\epsilon\cdot i\epsilon/(1+i^2\epsilon^2), and no algebraic identity collapses it. We need a way to evaluate integrals without adding slices at all.

The breakthrough comes from treating the upper limit as a variable. Fix a base point aa and define the area-so-far function

F(x)=∫axf(y) dy,(22.6.2)F(x) = \int_a^x f(y)\,dy, \tag{22.6.2}

which records the signed area accumulated from aa out to xx. This single function encodes every definite integral of ff: by additivity, the area over any interval [x1,x2][x_1,x_2] is simply the difference of two accumulated areas,

∫x1x2f(x) dx=F(x2)−F(x1),\int_{x_1}^{x_2} f(x)\,dx = F(x_2) - F(x_1),

as shown in Figure 22.6.3. Finding FF therefore solves the whole problem.

Figure 22.6.3:

The area under ff from x1x_1 to x2x_2 as the difference of two areas accumulated from the base point aa at the plot's left edge: ∫x1x2f dx=∫ax2f dx−∫ax1f dx\int_{x_1}^{x_2} f\,dx=\int_a^{x_2} f\,dx-\int_a^{x_1} f\,dx.

How does FF change when we nudge xx slightly to the right? Figure 22.6.4 shows the accumulated area up to xx alongside the thin strip of width ϵ\epsilon added by moving to x+ϵx+\epsilon. That strip is nearly a rectangle of height f(x)f(x), so F(x+ϵ)−F(x)≈ϵf(x)F(x+\epsilon)-F(x)\approx\epsilon f(x). Dividing by ϵ\epsilon suggests that F′(x)=f(x)F'(x)=f(x).

Figure 22.6.4:

The area-so-far F(x)F(x) under f(y)=y/(1+y2)f(y)=y/(1+y^2) from a=0a=0 to x=1.2x=1.2 (light), and the strip added by moving to x+ϵx+\epsilon (dark). The strip is close to the dashed rectangle of height f(x)f(x), so F(x+ϵ)−F(x)≈ϵf(x)F(x+\epsilon)-F(x)\approx\epsilon f(x).

Theorem (Fundamental theorem of calculus). Let ff be Riemann integrable on [a,b][a,b], let F(x)=∫axf(y) dyF(x)=\int_a^x f(y)\,dy, and let ff be continuous at a point x∈(a,b)x\in(a,b). Then FF is differentiable at xx and

dFdx(x)=f(x).(22.6.3)\frac{dF}{dx}(x) = f(x). \tag{22.6.3}

In words, the rate at which area accumulates equals the current height of the curve.

Proof. Nudge xx by ϵ>0\epsilon>0 and look at the added area. By (22.6.2) and additivity, the change is a single sliver,

F(x+ϵ)−F(x)=∫xx+ϵf(y) dy.F(x+\epsilon) - F(x) = \int_x^{x+\epsilon} f(y)\,dy .

Let mϵ=inf⁡[x,x+ϵ]fm_\epsilon = \inf_{[x,x+\epsilon]} f and Mϵ=sup⁡[x,x+ϵ]fM_\epsilon = \sup_{[x,x+\epsilon]} f be the tightest constant bounds on ff over this sliver; both are finite because an integrable function is bounded. Since mϵ≤f≤Mϵm_\epsilon\le f\le M_\epsilon throughout [x,x+ϵ][x,x+\epsilon], monotonicity of the integral traps the sliver's area between two rectangles of width ϵ\epsilon:

ϵ mϵ ≤ F(x+ϵ)−F(x) ≤ ϵ Mϵ.\epsilon\, m_\epsilon \ \le\ F(x+\epsilon) - F(x)\ \le\ \epsilon\, M_\epsilon .

Now divide through by ϵ\epsilon. Because ff is continuous at xx, for any δ>0\delta>0 the entire interval [x,x+ϵ][x,x+\epsilon] eventually lies inside the region where ∣f(y)−f(x)∣<δ|f(y)-f(x)|\lt \delta. Both mϵm_\epsilon and MϵM_\epsilon therefore converge to f(x)f(x) as ϵ→0\epsilon \to 0, and the squeeze forces lim⁡ϵ→0F(x+ϵ)−F(x)ϵ=f(x)\lim_{\epsilon\to 0}\frac{F(x+\epsilon)-F(x)}{\epsilon}=f(x). When ϵ<0\epsilon\lt 0, the sliver sits to the left of xx, and the same bounds hold with both sign flips canceling in the difference quotient. That limit is F′(x)F'(x). ■\blacksquare

Notice that the proof used only monotonicity and additivity, the two properties we read off the definition. The theorem turns the problem of finding an area into the problem of finding an antiderivative, a function GG satisfying G′=fG'=f, which we can often read straight off the derivative table in Section 22.1.2. Any antiderivative yields the definite integral via the evaluation rule: if ff is continuous on [a,b][a,b] and G′=fG'=f on all of [a,b][a,b], then

∫abf(x) dx=G(b)−G(a).(22.6.4)\int_a^b f(x)\,dx = G(b) - G(a). \tag{22.6.4}

Why does any antiderivative work, not just FF? Because FF and GG share the same derivative ff on (a,b)(a,b), so their difference G−FG-F has derivative zero and must be constant by the mean value theorem (Section 22.1.3). That additive constant cancels out in G(b)−G(a)=F(b)−F(a)=∫abf dxG(b)-G(a)=F(b)-F(a)=\int_a^b f\,dx.

The requirement "on all of [a,b][a,b]" is essential. Since (−1/x)′=x−2(-1/x)'=x^{-2}, blindly applying the rule gives ∫−11x−2 dx=[−1/x]−11=−2\int_{-1}^1x^{-2}\,dx=[-1/x]_{-1}^1=-2, a negative answer for a strictly positive integrand. The rule does not apply here because G′=fG'=f breaks down at x=0x=0, where neither function is defined; in fact the integral diverges (Section 22.6.2.2).

Read backwards, every derivative formula becomes an integral: (y3)′=3y2(y^3)'=3y^2 gives ∫01y2 dy=13\int_0^1y^2\,dy=\tfrac13 without a single slice, and (et)′=et(e^t)'=e^t gives ∫0xet dt=ex−1\int_0^xe^t\,dt=e^x-1. For our running example, try G(x)=12log⁡(1+x2)G(x)=\tfrac12\log(1+x^2). By the chain rule, G′(x)=12⋅2x1+x2=x1+x2G'(x)=\tfrac12\cdot\frac{2x}{1+x^2}=\frac{x}{1+x^2}, so

∫02x1+x2 dx=G(2)−G(0)=12log⁡5−12log⁡1=12log⁡5,\int_0^2\frac{x}{1+x^2}\,dx=G(2)-G(0)=\tfrac12\log5-\tfrac12\log1=\tfrac12\log5,

confirming the limit our Riemann sums were approaching.

The error of the left rule. The evaluation rule also explains where the constant 0.20.2 in the left-sum error came from. On the slice starting at xix_i, a first-order expansion gives f(x)≈f(xi)+f′(xi)(x−xi)f(x)\approx f(x_i)+f'(x_i)(x-x_i). Integrating over [xi,xi+ϵ][x_i,x_i+\epsilon] shows that the true area of the slice exceeds its rectangle ϵf(xi)\epsilon f(x_i) by roughly ϵ22f′(xi)\tfrac{\epsilon^2}2f'(x_i). Summing these triangular excesses across all slices yields ϵ2\tfrac\epsilon2 times a left sum of f′f', which approximates ϵ2∫abf′ dx=ϵ2(f(b)−f(a))\tfrac\epsilon2\int_a^bf'\,dx=\tfrac\epsilon2(f(b)-f(a)). To first order in ϵ\epsilon,

left sum−∫abf(x) dx≈ϵ2(f(a)−f(b)).\text{left sum}-\int_a^b f(x)\,dx\approx\frac\epsilon2\bigl(f(a)-f(b)\bigr).

For x2x^2 on [0,1][0,1] this gives −ϵ2=−12N-\tfrac\epsilon2=-\tfrac1{2N}, matching the leading error term we found by hand. For the running example, f(0)=0f(0)=0 and f(2)=0.4f(2)=0.4 give −0.2 ϵ-0.2\,\epsilon. This estimate is numerical analysis rather than pure calculus, yet it accounts for the residual error in three more experiments in this section and serves as the baseline against which random sampling is judged in Section 24.5.1.7.

The fundamental theorem actually tells us more than ∫02f=G(2)−G(0)\int_0^2f=G(2)-G(0): the area-so-far function F(x)F(x) must equal G(x)−G(0)G(x)-G(0) at every xx. Let us verify this by computing FF as a cumulative left sum across [0,2][0,2] and comparing it with G(x)−G(0)G(x)-G(0) at every grid point. The two will not match to machine precision, because the left sum on [0,x][0,x] carries the bias ϵ2(f(0)−f(x))\tfrac\epsilon2\bigl(f(0)-f(x)\bigr). That bias is largest where ff peaks, at x=1x=1 where f(1)=12f(1)=\tfrac12, so the maximum discrepancy across the interval should be ϵ4\tfrac\epsilon4.

G = lambda x: np.log(1 + x**2) / 2             # antiderivative of f
for eps in [1e-2, 1e-3, 1e-4]:
    x = eps * np.arange(round(2 / eps))        # left ends of the slices of [0, 2]
    F = np.cumsum(eps * f(x))                  # F[k]: left sum on [0, x_k + eps]
    gap = np.abs(F - (G(x + eps) - G(0))).max()
    print(f'eps={eps:.0e}  max over x of |F(x) - (G(x) - G(0))| = {gap:.2e}')
eps=1e-02  max over x of |F(x) - (G(x) - G(0))| = 2.51e-03
eps=1e-03  max over x of |F(x) - (G(x) - G(0))| = 2.50e-04
eps=1e-04  max over x of |F(x) - (G(x) - G(0))| = 2.50e-05

At every slice width, the maximum discrepancy is ϵ4\tfrac\epsilon4, just as predicted. The cumulative sum tracks the antiderivative across the entire interval, not only at the right endpoint x=2x=2.

22.6.2.2 Improper Integrals#

The normal, exponential, and many other probability densities live on unbounded domains, whereas (22.6.1) defines integrals only over a finite interval [a,b][a,b]. We extend the definition the same way we built it, by taking a limit. The improper integral over [a,∞)[a,\infty) is

∫a∞f(x) dx=lim⁡b→∞∫abf(x) dx,(22.6.5)\int_a^\infty f(x)\,dx = \lim_{b\to\infty}\int_a^b f(x)\,dx , \tag{22.6.5}

the area accumulated out to bb in the limit of large bb. If this limit exists and is finite, the integral converges; otherwise it diverges. To integrate over the entire real line, we split ∫−∞∞f dx\int_{-\infty}^\infty f\,dx at any convenient point into two one-sided improper integrals, and both must converge independently. A symmetric limit is not enough: ∫−bbx dx=0\int_{-b}^b x\,dx=0 for every bb, yet ∫0∞x dx=∞\int_0^\infty x\,dx=\infty, so ∫−∞∞x dx\int_{-\infty}^\infty x\,dx does not exist.

The power law x−sx^{-s} (with exponent s>0s>0) is the standard benchmark for deciding whether a tail decays fast enough to enclose finite area. Applying the evaluation rule on [1,b][1,b] and taking b→∞b\to\infty gives

∫1bx−s dx=b1−s−11−s→ b→∞ {1s−1,s>1 (converges),∞,s≤1 (diverges).\begin{aligned} \int_1^b x^{-s}\,dx &= \frac{b^{1-s}-1}{1-s} \\ &\xrightarrow{\ b\to\infty\ } \begin{cases} \dfrac{1}{s-1}, & s>1\ \text{(converges)},\\[1ex] \infty, & s\le 1\ \text{(diverges)}.\end{cases} \end{aligned}

(At s=1s=1 the expression reads 0/00/0; the definite integral is log⁡b\log b, which is the limit of the formula as s→1s\to 1 and diverges as b→∞b\to\infty.) Thus ∫1∞x−2 dx=1\int_1^\infty x^{-2}\,dx=1 whereas ∫1∞x−1 dx=∞\int_1^\infty x^{-1}\,dx=\infty: the dividing line between finite and infinite area lies right at s=1s=1.

Power laws are the canonical heavy-tailed distributions (Section 24.1, which also examines how heavy tails affect averages). For a density with tail p(x)∝x−sp(x)\propto x^{-s}, the normalizing constant is finite only when s>1s>1, and the mean, tested by applying the same criterion to x⋅x−s=x1−sx\cdot x^{-s}=x^{1-s}, is finite only when s>2s>2.

The same limiting device handles an integrand that blows up at an endpoint: ∫01f dx=lim⁡a→0+∫a1f dx\int_0^1 f\,dx=\lim_{a\to0^+}\int_a^1 f\,dx. For the power law x−sx^{-s}, the condition reverses:

∫01x−s dx=lim⁡a→0+1−a1−s1−s=11−sfor s<1,\int_0^1x^{-s}\,dx=\lim_{a\to0^+}\frac{1-a^{1-s}}{1-s}=\frac1{1-s}\quad\text{for } s\lt 1,

while the integral diverges for s≥1s\ge1. At s=12s=\tfrac12, for instance, x−1/2x^{-1/2} shoots to infinity at 00, yet the area under it is only 22. Near infinity, a power law must fall faster than 1/x1/x to have finite area; near zero, it must grow more slowly than 1/x1/x.

When we approximate an improper integral numerically, two distinct errors enter: we cut off the domain at a finite bb, and we sum slices of finite width ϵ\epsilon. For ∫0∞e−x dx=1\int_0^\infty e^{-x}\,dx = 1, we can separate the two. Below we print the exact partial integral ∫0be−x dx=1−e−b\int_0^b e^{-x}\,dx = 1-e^{-b} (from the antiderivative −e−x-e^{-x}) next to a left sum with ϵ=10−3\epsilon = 10^{-3}.

for b in [1, 2, 5, 10, 20]:
    left = left_sum(lambda x: np.exp(-x), 0, b, 1e-3)
    print(f'b={b:<3}  left sum={left:.6f}  exact 1-e^-b={1 - math.exp(-b):.6f}')
b=1    left sum=0.632437  exact 1-e^-b=0.632121
b=2    left sum=0.865097  exact 1-e^-b=0.864665
b=5    left sum=0.993759  exact 1-e^-b=0.993262
b=10   left sum=1.000455  exact 1-e^-b=0.999955
b=20   left sum=1.000500  exact 1-e^-b=1.000000

The exact partial integrals converge to 11 rapidly: the truncation error from stopping at bb is e−be^{-b}, already below the sixth decimal place by b=20b=20. The left sums, however, settle near 1.00051.0005 rather than 11. That residual is discretization error, our left-rule bias ϵ2(f(0)−f(b))→ϵ2=0.0005\tfrac{\epsilon}{2}\bigl(f(0)-f(b)\bigr)\to\tfrac{\epsilon}{2}=0.0005. To leading order the two errors simply add: pushing bb higher removes truncation error, while shrinking ϵ\epsilon removes discretization error.

22.6.2.3 Integration by Parts#

Every differentiation rule, read through the evaluation rule, yields a matching integration rule. The product rule becomes integration by parts.

For continuously differentiable functions uu and vv on [a,b][a,b],

∫abu(x) v′(x) dx=[ u(x) v(x) ]ab−∫abu′(x) v(x) dx,(22.6.6)\int_a^b u(x)\,v'(x)\,dx = \Bigl[\,u(x)\,v(x)\,\Bigr]_a^b - \int_a^b u'(x)\,v(x)\,dx , \tag{22.6.6}

where [ h(x) ]ab[\,h(x)\,]_a^b is shorthand for h(b)−h(a)h(b)-h(a). The proof takes one line: by the product rule, uvuv is an antiderivative of u′v+uv′u'v + uv', so (22.6.4) gives ∫ab(u′v+uv′) dx=[ u(x)v(x) ]ab\int_a^b (u'v + uv')\,dx = [\,u(x)v(x)\,]_a^b, and subtracting ∫abu′v dx\int_a^b u'v\,dx from both sides yields (22.6.6).

What this formula does is shift a derivative from one factor onto the other at the cost of a boundary term. It pays off whenever the new integrand u′vu'v is simpler than uv′uv'. Choosing u(x)=xu(x)=x and v′(x)=e−xv'(x)=e^{-x} (so u′=1u'=1 and v=−e−xv=-e^{-x}), applying (22.6.6) on [0,b][0,b], and letting b→∞b\to\infty gives

∫0∞x e−x dx=[ −x e−x ]0∞+∫0∞e−x dx=0+1=1.\int_0^\infty x\,e^{-x}\,dx = \Bigl[\,-x\,e^{-x}\,\Bigr]_0^\infty + \int_0^\infty e^{-x}\,dx = 0 + 1 = 1 .

The boundary term vanishes because xe−x→0x e^{-x}\to 0 at both endpoints, leaving the improper integral we just evaluated. This integral is the mean of the exponential distribution (Section 24.3).

Because expectations are integrals of products, a recurring trick in probability and machine learning is to shift a derivative off an intractable factor and onto a tractable one. The bell curve shows this technique at its cleanest. Consider the unnormalized bell weight w(z)=e−z2/2w(z)=e^{-z^2/2}, which satisfies w′(z)=−z w(z)w'(z)=-z\,w(z). Let gg be continuously differentiable with g(z)w(z)→0g(z)w(z)\to0 as z→±∞z\to\pm\infty, and suppose the two integrals below converge. Integrating by parts on [−a,b][-a,b] and then taking a→∞a\to\infty and b→∞b\to\infty separately yields

∫−∞∞g′(z) w(z) dz=[ g(z) w(z) ]−∞∞−∫−∞∞g(z) w′(z) dz=∫−∞∞z g(z) w(z) dz.(22.6.7)\int_{-\infty}^{\infty}g'(z)\,w(z)\,dz =\Bigl[\,g(z)\,w(z)\,\Bigr]_{-\infty}^{\infty}-\int_{-\infty}^{\infty}g(z)\,w'(z)\,dz =\int_{-\infty}^{\infty}z\,g(z)\,w(z)\,dz . \tag{22.6.7}

Under the bell weight, multiplying by zz has the same effect as differentiating gg. Both hypotheses hold for every polynomial gg. Taking g(z)=zg(z)=z gives ∫z2w dz=∫w dz\int z^2 w\,dz=\int w\,dz: the mean of z2z^2 under the bell weight is 11, regardless of what the normalizing constant ∫w dz\int w\,dz turns out to be (we will show it is 2π\sqrt{2\pi} in (22.6.14)). Taking g(z)=z3g(z)=z^3 gives ∫z4w dz=3∫z2w dz=3∫w dz\int z^4 w\,dz=3\int z^2 w\,dz=3\int w\,dz, so the mean of z4z^4 is 33. Once ww is normalized into the standard normal density p=w/2πp=w/\sqrt{2\pi}, this becomes E[g′(Z)]=E[Z g(Z)]\mathbb{E}[g'(Z)]=\mathbb{E}[Z\,g(Z)], known as Stein's identity for the standard normal. Shifting a derivative from an unknown factor onto a known one is also the key step behind score matching (Section 26.6, (Hyvärinen, 2005)). In Rd\mathbb{R}^d, the corresponding rule moves a divergence instead of a one-dimensional derivative; Section 26.5.2.1 introduces the divergence, the Laplacian, and that multivariable identity where they are first needed.

22.6.2.4 Substitution#

Reading the chain rule backwards through the evaluation rule produces the substitution rule. Suppose uu is continuously differentiable on [a,b][a,b] and ff is continuous on an interval containing u([a,b])u([a,b]), with antiderivative GG. By the chain rule, (G∘u)′(x)=f(u(x)) u′(x)(G\circ u)'(x)=f(u(x))\,u'(x), so

∫abf(u(x)) u′(x) dx=∫ab(G∘u)′(x) dx=G(u(b))−G(u(a))=∫u(a)u(b)f(y) dy.\int_a^b f(u(x))\,u'(x)\,dx=\int_a^b (G\circ u)'(x)\,dx=G(u(b))-G(u(a))=\int_{u(a)}^{u(b)}f(y)\,dy .

Read from right to left, this is the change-of-variables formula

∫u(a)u(b)f(y) dy=∫abf(u(x)) dudx dx.(22.6.8)\int_{u(a)}^{u(b)} f(y)\,dy = \int_a^b f(u(x))\,\frac{du}{dx}\,dx . \tag{22.6.8}

In words, an integral over yy can be rewritten as an integral over xx provided we multiply the integrand by the local stretch factor du/dxdu/dx. Note that uu does not even need to be monotone.

A single thin slice makes the stretch factor transparent. Partition [a,b][a,b] into slices of width ϵ\epsilon. The map uu carries the slice at xx to a slice of width approximately ϵ u′(x)\epsilon\,u'(x) at y=u(x)y=u(x), where the curve has height f(y)=f(u(x))f(y)=f(u(x)). Its area is therefore f(u(x)) u′(x) ϵf(u(x))\,u'(x)\,\epsilon, which is the quantity the xx-integral sums (Figure 22.6.5).

Figure 22.6.5:

A thin sliver under the substitution y=u(x)y=u(x). Left, the xx side (the right-hand side of the formula): a sliver of width ϵ\epsilon at xx and height f(u(x))f(u(x)). Right, the yy side: its image, of width ϵ u′(x)\epsilon\,u'(x) and the same height. Matching the two areas requires the factor du/dxdu/dx.

In practice, substitution works by spotting the pattern f(u(x)) u′(x)f(u(x))\,u'(x) inside an integrand. In ∫01x e−x2 dx\int_0^1 x\,e^{-x^2}\,dx, set u(x)=x2u(x)=x^2 so u′(x)=2xu'(x)=2x: the integrand is 12e−u(x)u′(x)\tfrac12 e^{-u(x)}u'(x), and

∫01x e−x2 dx=12∫01e−y dy=1−e−12≈0.316.\int_0^1x\,e^{-x^2}\,dx=\frac12\int_0^1e^{-y}\,dy=\frac{1-e^{-1}}2\approx 0.316 .

Here the factor xx supplied the u′(x)u'(x) that substitution needs. Remove that xx and we are left with ∫e−x2 dx\int e^{-x^2}\,dx, which has no elementary antiderivative and is the very integral behind the bell curve's normalizer 1/2π1/\sqrt{2\pi}. To evaluate it in (22.6.13), we will obtain the missing factor by moving to two dimensions and switching to polar coordinates.

22.6.3 Multiple Integrals#

From this point on we quote two standard theorems without proof, both from (Folland, 1999): Fubini's theorem and the multivariable change-of-variables formula.

22.6.3.1 Double Integrals and Fubini's Theorem#

Because our route to ∫e−x2 dx\int e^{-x^2}\,dx passes through two dimensions, we first extend integration from intervals to regions of the plane. Consider the two-dimensional bell surface f(x,y)=e−x2−y2f(x,y)=e^{-x^2-y^2} over the square [−2,2]2[-2,2]^2, which encloses a volume above the base plane. We approximate that volume just as we approximated areas: tile the base with ϵ×ϵ\epsilon\times\epsilon squares, erect on each square a column of height ff, and sum the column volumes (Figure 22.6.6). For a function ff on a rectangle R=[a,b]×[c,d]R=[a,b]\times[c,d], the limit of these box sums as ϵ→0\epsilon\to0 is the double integral ∬Rf(x,y) dx dy\iint_R f(x,y)\,dx\,dy, the signed volume beneath the surface.

Figure 22.6.6:

The bell surface z=e−x2−y2z=e^{-x^2-y^2} over the square [−2,2]2[-2,2]^2. Tiling the base with ϵ×ϵ\epsilon\times\epsilon squares (ϵ=0.5\epsilon=0.5) and placing a box of height ff on each approximates the volume under the surface; the highlighted column of boxes at a fixed xx corresponds to one inner sum in Fubini's theorem.

How can we compute such a volume using our one-dimensional tools? Any finite sum can be totaled in whatever order we like. Indexing the grid squares by ii along xx and jj along yy, we can sum the boxes column by column (Figure 22.6.7):

∑i,jϵ2f(a+ϵi,c+ϵj)=∑iϵ(∑jϵ f(a+ϵi,c+ϵj)).\sum_{i,j}\epsilon^2 f(a+\epsilon i,c+\epsilon j) =\sum_i \epsilon\Bigl(\sum_j \epsilon\, f(a+\epsilon i,c+\epsilon j)\Bigr).

The inner sum is the left-endpoint approximation to ∫cdf(a+ϵi,y) dy\int_c^d f(a+\epsilon i,y)\,dy, the cross-sectional area of the surface at x=a+ϵix=a+\epsilon i (the highlighted column in Figure 22.6.6), and the outer sum integrates that slice area across xx.

Figure 22.6.7:

Totalling a grid of ϵ×ϵ\epsilon\times\epsilon cells with corner (a,c)(a,c), indexed by ii along xx and jj along yy. (1) Sum each column, at fixed ii, over jj. (2) Add the column totals from left to right. Reordering a finite sum changes nothing; this discrete fact underlies iterated integration.

Reordering a finite grid sum is elementary, but ensuring that the equality survives the limit ϵ→0\epsilon\to0 requires a theorem and a condition. Fubini's theorem states that if ff is absolutely integrable on RR, meaning ∬R∣f(x,y)∣ dx dy<∞\iint_R|f(x,y)|\,dx\,dy\lt \infty, then the double integral equals either iterated integral:

∬Rf(x,y) dx dy=∫cd ⁣(∫abf(x,y) dx)dy=∫ab ⁣(∫cdf(x,y) dy)dx.(22.6.9)\iint_R f(x,y)\,dx\,dy = \int_c^{d}\!\left(\int_a^{b} f(x,y)\,dx\right)dy = \int_a^{b}\!\left(\int_c^{d} f(x,y)\,dy\right)dx . \tag{22.6.9}

In geometric terms, a volume can be computed slice by slice in either direction. When f≥0f\ge0, the same equality holds with no integrability check at all, allowing all three sides to equal +∞+\infty (Tonelli's theorem). Probability densities, squared losses, and other nonnegative integrands therefore require no verification; for a signed integrand, however, we must check ∬∣f∣<∞\iint|f|\lt \infty first. Fubini's theorem is at work whenever we marginalize a variable out of a joint density or swap an expectation with another integral.

The most common special case is a product integrand f(x,y)=g(x)h(y)f(x,y)=g(x)h(y). Because g(x)g(x) is constant with respect to yy, it pulls straight out of the inner integral, ∫cdg(x)h(y) dy=g(x)∫cdh(y) dy\int_c^d g(x)h(y)\,dy=g(x)\int_c^d h(y)\,dy, leaving

∬Rg(x) h(y) dx dy=∫abg(x) dx∫cdh(y) dy.(22.6.10)\iint_R g(x)\,h(y)\,dx\,dy=\int_a^b g(x)\,dx\int_c^d h(y)\,dy . \tag{22.6.10}

A product integrand integrates factor by factor. Crucially, the two-dimensional bell factors in this way, e−x2−y2=e−x2e−y2e^{-x^2-y^2}=e^{-x^2}e^{-y^2}, and our evaluation of the Gaussian integral below rests on this observation.

The absolute-integrability hypothesis is not a mere formality. Consider f(x,y)=(x2−y2)/(x2+y2)2f(x,y)=(x^2-y^2)/(x^2+y^2)^2 on [0,1]2[0,1]^2. A quick differentiation shows that ∂y(y/(x2+y2))=f(x,y)\partial_y\bigl(y/(x^2+y^2)\bigr)=f(x,y), so the evaluation rule gives ∫01f(x,y) dy=11+x2\int_0^1 f(x,y)\,dy=\frac1{1+x^2} for x>0x>0, and integrating over xx yields ∫01dx1+x2=arctan⁡1=π4\int_0^1\frac{dx}{1+x^2}=\arctan 1=\frac\pi4. Yet f(x,y)=−f(y,x)f(x,y)=-f(y,x), so integrating in the reverse order gives −π4-\frac\pi4. The two orders disagree because ∬∣f∣=∞\iint|f|=\infty: near the origin, ∣f∣|f| grows like the inverse square of the distance, and its total volume diverges.

When the domain DD is not a rectangle, ∫Df(x) dx\int_D f(\mathbf x)\,d\mathbf x is defined by zero-extension: set ff to 00 outside DD and integrate over any rectangle that contains DD.

22.6.3.2 Change of Variables in Many Dimensions#

The one-dimensional stretch factor du/dxdu/dx generalizes naturally to higher dimensions, and linear maps already show the form it must take. A linear map scales every area or volume by the absolute value of its determinant (Section 21.2), while the sign of the determinant merely tracks orientation. For example, the map ϕ(u,v)=(au,bv)\boldsymbol\phi(u,v)=(au,bv) with a,b>0a,b>0 has determinant abab and stretches the unit disc (of area π\pi) into the ellipse x2/a2+y2/b2≤1x^2/a^2+y^2/b^2\le1, whose area is therefore πab\pi ab.

Locally, a smooth nonlinear map looks linear, with its Jacobian matrix serving as the linear approximation; the volume scale factor simply varies from point to point. Let Ω⊆Rn\Omega\subseteq\mathbb{R}^n be open and let ϕ:Ω→Rn\boldsymbol{\phi}:\Omega\to\mathbb{R}^n be a C1C^1-diffeomorphism onto its image: ϕ\boldsymbol{\phi} is continuously differentiable and injective, and its Jacobian Jϕ\mathbf J_{\boldsymbol\phi} (the matrix of partial derivatives from Section 22.4) satisfies det⁡Jϕ(x)≠0\det\mathbf J_{\boldsymbol\phi}(\mathbf{x})\neq 0 everywhere on Ω\Omega. Injectivity prevents the map from folding space onto itself, and a nonzero determinant prevents it from flattening a region to a lower dimension. Under these conditions, for any absolutely integrable ff,

∫ϕ(Ω)f(y) dy=∫Ωf(ϕ(x)) ∣det⁡Jϕ(x)∣ dx.(22.6.11)\int_{\boldsymbol{\phi}(\Omega)} f(\mathbf{y})\,d\mathbf{y} = \int_{\Omega} f(\boldsymbol{\phi}(\mathbf{x}))\, \bigl|\det \mathbf J_{\boldsymbol\phi}(\mathbf{x})\bigr|\,d\mathbf{x}. \tag{22.6.11}

An infinitesimal cube of volume dxd\mathbf x at x\mathbf x maps to an infinitesimal parallelepiped of volume ∣det⁡Jϕ(x)∣ dx|\det\mathbf J_{\boldsymbol\phi}(\mathbf x)|\,d\mathbf x at y=ϕ(x)\mathbf y=\boldsymbol\phi(\mathbf x), and the Jacobian determinant adjusts the integrand for that local distortion. Figure 22.6.8 places the one- and two-dimensional pictures side by side.

Figure 22.6.8:

Left: one-dimensional substitution scales a segment of length ϵ\epsilon by u′(x)u'(x). Right: in two dimensions, a linear map ϕ\boldsymbol\phi sends the unit square to a parallelogram whose area is the volume factor ∣det⁡Jϕ∣|\det\mathbf J_{\boldsymbol\phi}|.

Why does (22.6.11) carry the absolute value ∣det⁡Jϕ∣|\det\mathbf J_{\boldsymbol\phi}| rather than det⁡Jϕ\det\mathbf J_{\boldsymbol\phi}? Because the left-hand side integrates over an unoriented set, not between ordered endpoints. In one dimension, the order of the limits carries the sign: if uu is decreasing, the limits in (22.6.8) run backwards while u′<0u'\lt 0, so the two minus signs cancel and we can equivalently integrate over the image interval with ∣u′∣|u'|. Regions in Rn\mathbb R^n have no natural ordering, so only this unsigned form generalizes.

When ff is a probability density, (22.6.11) tells us how a density transforms under a smooth invertible map, which is how a normalizing flow computes the density of its output (Section 24.2).

22.6.3.3 The Gaussian Integral#

The normalizing constant 1/2π1/\sqrt{2\pi} of the bell curve comes from the one-dimensional integral ∫−∞∞e−x2 dx\int_{-\infty}^\infty e^{-x^2}\,dx. Here the fundamental theorem cannot give us a closed form: an antiderivative certainly exists because e−x2e^{-x^2} is continuous, but it is a fundamentally new function that cannot be written in terms of elementary ones. Surprisingly, the integral over the entire real line can still be evaluated in closed form by taking a detour through two dimensions. The argument takes three steps and is the most elegant calculation in the section. (Normalized, the antiderivative is the error function erf⁡(x)=2π∫0xe−t2 dt\operatorname{erf}(x)=\frac2{\sqrt\pi}\int_0^x e^{-t^2}\,dt, which tends to 11 as x→∞x\to\infty by the result we are about to prove; standard libraries provide it as math.erf.)

I. Square and factor. On the square [−b,b]2[-b,b]^2, the product rule (22.6.10) gives ∬[−b,b]2e−x2−y2 dx dy=(∫−bbe−x2 dx)2\iint_{[-b,b]^2}e^{-x^2-y^2}\,dx\,dy=\bigl(\int_{-b}^b e^{-x^2}\,dx\bigr)^2. Letting b→∞b\to\infty on both sides yields

(∫−∞∞e−x2 dx) ⁣2=lim⁡b→∞∬[−b,b]2e−x2−y2 dx dy=∬R2e−x2−y2 dx dy.(22.6.12)\left(\int_{-\infty}^{\infty} e^{-x^2}\,dx\right)^{\!2} = \lim_{b\to\infty}\iint_{[-b,b]^2} e^{-x^2-y^2}\,dx\,dy = \iint_{\mathbb R^2} e^{-x^2-y^2}\,dx\,dy . \tag{22.6.12}

The square of our one-dimensional integral is simply the volume under the two-dimensional bell, and that surface is rotationally symmetric around the origin.

II. Polar coordinates. Rotational symmetry invites polar coordinates, ϕ(r,θ)=(rcos⁡θ,rsin⁡θ)\boldsymbol{\phi}(r,\theta)=(r\cos\theta, r\sin\theta), on the open set Ω=(0,∞)×(0,2π)\Omega=(0,\infty)\times(0,2\pi), where the map is injective. Its Jacobian determinant is

∣det⁡Jϕ∣=∣det⁡[cos⁡θ−rsin⁡θsin⁡θrcos⁡θ]∣=r(cos⁡2θ+sin⁡2θ)=r.\bigl|\det \mathbf J_{\boldsymbol\phi}\bigr| = \left|\det\begin{bmatrix}\cos\theta & -r\sin\theta\\ \sin\theta & r\cos\theta\end{bmatrix}\right| = r(\cos^2\theta + \sin^2\theta) = r .

Geometrically, a polar cell with radial side drdr and arc length r dθr\,d\theta has area approximately r dr dθr\,dr\,d\theta (Figure 22.6.9), reflecting the fact that cells farther from the origin are wider. Crucially, this factor rr supplies the missing factor xx from our substitution example ∫01x e−x2 dx\int_0^1 x\,e^{-x^2}\,dx.

Figure 22.6.9:

A polar grid with one cell shaded: radial side drdr and arc side r dθr\,d\theta, giving an area of approximately r dr dθr\,dr\,d\theta. Switching to polar coordinates multiplies the integrand by ∣det⁡Jϕ∣=r|\det\mathbf J_{\boldsymbol\phi}|=r.

III. Integrate. Applying (22.6.11) and using the antiderivative −12e−r2-\tfrac12 e^{-r^2} of re−r2r e^{-r^2}, we obtain

∬R2e−x2−y2 dx dy=∫02π ⁣ ⁣∫0∞r e−r2 dr dθ=2π⋅12=π.\iint_{\mathbb{R}^2} e^{-x^2-y^2}\,dx\,dy = \int_0^{2\pi}\!\!\int_0^\infty r\,e^{-r^2}\,dr\,d\theta = 2\pi\cdot\frac12 = \pi .

Taking the positive square root of (22.6.12) gives

∫−∞∞e−x2 dx=π.(22.6.13)\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi} . \tag{22.6.13}

Thus the total area under e−x2e^{-x^2} is π≈1.7725\sqrt\pi\approx 1.7725.

Three technical points make this argument completely rigorous. First, because the integrand is nonnegative, integrals over expanding squares and over expanding discs converge to the same limit: every disc fits inside some square and every square inside some disc, so the shape of the growing region does not matter. Second, the polar map omits the nonnegative ray θ=0\theta=0, which has zero area and contributes nothing to the integral. Third, we apply the change of variables on the bounded rectangles (0,b)×(0,2π)(0,b)\times(0,2\pi), where the integrand is bounded and continuous, and let b→∞b\to\infty afterward.

The normalizing constant of the standard normal now follows from a single substitution. Setting z=2 xz=\sqrt2\,x in (22.6.8) gives

∫−∞∞e−z2/2 dz=2∫−∞∞e−x2 dx=2π.(22.6.14)\int_{-\infty}^{\infty}e^{-z^2/2}\,dz=\sqrt2\int_{-\infty}^{\infty}e^{-x^2}\,dx=\sqrt{2\pi}. \tag{22.6.14}

Dividing the bell e−z2/2e^{-z^2/2} by 2π≈2.5066\sqrt{2\pi}\approx 2.5066 scales its total area to 11, which is where the constant in the standard normal density comes from.

Let us check step I numerically: do the expanding squares [−b,b]2[-b,b]^2 really exhaust the plane and converge to π\pi? The code below computes the two-dimensional grid sum over [−b,b]2[-b,b]^2 at ϵ=0.01\epsilon=0.01 alongside the exact square volume (∫−bbe−x2 dx)2=πerf⁡(b)2\bigl(\int_{-b}^b e^{-x^2}\,dx\bigr)^2=\pi\operatorname{erf}(b)^2 and the limiting value π\pi.

eps = 0.01
for b in [1, 2, 3, 6]:
    g = -b + eps * np.arange(round(2 * b / eps))    # left ends of the slices
    x, y = np.meshgrid(g, g, indexing='ij')
    grid = np.sum(eps**2 * np.exp(-x**2 - y**2))
    print(f'b={b}  grid sum={grid:.6f}  pi*erf(b)^2={math.pi * math.erf(b)**2:.6f}'
          f'  pi={math.pi:.6f}')
b=1  grid sum=2.230949  pi*erf(b)^2=2.230985  pi=3.141593
b=2  grid sum=3.112266  pi*erf(b)^2=3.112270  pi=3.141593
b=3  grid sum=3.141454  pi*erf(b)^2=3.141454  pi=3.141593
b=6  grid sum=3.141593  pi*erf(b)^2=3.141593  pi=3.141593

The grid sums track πerf⁡(b)2\pi\operatorname{erf}(b)^2 closely and climb to π\pi; by b=3b=3, the volume left outside the square is only about 10−410^{-4}. Agreement to four or more decimal places at ϵ=0.01\epsilon=0.01 has a simple explanation: for an even integrand on a symmetric interval, the left rule's first-order bias ϵ2(f(−b)−f(b))\tfrac\epsilon2\bigl(f(-b)-f(b)\bigr) vanishes identically.

We can now compute the standard normal probability P(−1≤Z≤1)≈0.68P(-1\le Z\le1)\approx0.68 as well. Substituting z=2 tz=\sqrt2\,t turns the area under p(z)=e−z2/2/2πp(z)=e^{-z^2/2}/\sqrt{2\pi} into an error function:

P(−1≤Z≤1)=12π∫−11e−z2/2 dz=1π∫−1/21/2e−t2 dt=erf⁡(1/2)≈0.683.P(-1\le Z\le1)=\frac{1}{\sqrt{2\pi}}\int_{-1}^1e^{-z^2/2}\,dz =\frac{1}{\sqrt\pi}\int_{-1/\sqrt2}^{1/\sqrt2}e^{-t^2}\,dt =\operatorname{erf}\bigl(1/\sqrt2\bigr)\approx 0.683 .

Both questions we asked about the bell curve are now answered, and the apparent paradox that p(0)≈0.40p(0)\approx 0.40 while P(Z=0)=0P(Z=0)=0 disappears: a density measures probability per unit length, and a single point is an interval of length zero.

One question from the opening remains open. Training a model through random sampling requires knowing how an area of this kind changes when a parameter of the density moves, and for that we need to differentiate an integral.

22.6.4 Summary#

The definite integral is the limit of sums of thin slices, measuring signed area under a curve. The fundamental theorem of calculus replaces that limit with antidifferentiation: because the area-so-far function satisfies F′=fF'=f, any antiderivative GG gives ∫abf dx=G(b)−G(a)\int_a^b f\,dx=G(b)-G(a). Integration by parts and substitution are the product and chain rules read backwards. In multiple dimensions, Fubini's theorem reduces volume integrals to iterated one-dimensional integrals, and the change-of-variables stretch factor becomes ∣det⁡Jϕ∣|\det\mathbf J_{\boldsymbol\phi}|, the local volume distortion; combined with polar coordinates, this yields ∫−∞∞e−x2 dx=π\int_{-\infty}^\infty e^{-x^2}\,dx=\sqrt\pi and the standard normal normalizing constant 2π\sqrt{2\pi}.

22.6.5 Exercises#

  1. Activations as accumulated areas. Let HH be the unit step, with H(t)=1H(t)=1 for t>0t>0 and H(t)=0H(t)=0 for t≤0t\le 0. Let ϕ(t)=e−t2/2/2π\phi(t)=e^{-t^2/2}/\sqrt{2\pi} be the standard Gaussian density and Φ(x)=∫−∞xϕ(t) dt\Phi(x)=\int_{-\infty}^x \phi(t)\,dt its distribution function.

    1. Show that ∫−∞xH(t) dt=ReLU(x)\int_{-\infty}^{x} H(t)\,dt=\mathrm{ReLU}(x). Which hypothesis of the fundamental theorem (22.6.3) fails at x=0x=0? What are the one-sided derivatives of the integral there?
    2. Write Φ(x)=Φ(0)+∫0xϕ(t) dt\Phi(x)=\Phi(0)+\int_0^x \phi(t)\,dt to conclude that Φ′=ϕ\Phi'=\phi. Then substitute t=2 st=\sqrt2\,s to show that Φ(x)=12(1+erf⁡(x/2))\Phi(x)=\tfrac12\bigl(1+\operatorname{erf}(x/\sqrt2)\bigr).
    3. The GELU activation of Section 4.1 is xΦ(x)x\Phi(x). Derive its derivative, find the points where the derivative is largest and smallest, and evaluate it there with math.erf. In which interval does the slope of GELU lie, and how does that interval compare with the slopes 00 and 11 of ReLU?
  2. Heavy tails. The Pareto density with tail index α>0\alpha>0 is p(x)=αx−α−1p(x)=\alpha x^{-\alpha-1} for x≥1x\ge 1 and p(x)=0p(x)=0 otherwise. The Cauchy density is p(x)=1π(1+x2)p(x)=\tfrac{1}{\pi(1+x^2)} on R\mathbb R.

    1. Show that the Pareto density is normalized for every α>0\alpha>0. For which α\alpha are E[X]\mathbb{E}[X] and E[X2]\mathbb{E}[X^2] finite? Compute E[X]\mathbb{E}[X] where it is finite.
    2. Show that the Cauchy density is normalized, using the antiderivative arctan⁡x\arctan x of 11+x2\tfrac{1}{1+x^2}.
    3. Show that ∫−bbx p(x) dx=0\int_{-b}^{b} x\,p(x)\,dx=0 for the Cauchy density and every b>0b>0. Why does the Cauchy density nevertheless have no mean under the definition of ∫−∞∞\int_{-\infty}^{\infty} that follows (22.6.5)? How fast does ∫0bx p(x) dx\int_0^b x\,p(x)\,dx grow with bb?
  3. Gamma function by parts. The Gamma function is Γ(t)=∫0∞ut−1e−u du\Gamma(t)=\int_0^\infty u^{t-1}e^{-u}\,du. For t<1t\lt 1 the integrand is unbounded at u=0u=0, and the integral near 00 is defined by a limit, ∫01=lim⁡a→0+∫a1\int_0^1=\lim_{a\to 0^+}\int_a^1, as in Section 22.6.2.2.

    1. For which tt does the integral converge at u=0u=0? Compare the condition with the test for ∫01x−s dx\int_0^1x^{-s}\,dx in Section 22.6.2.2.
    2. Integrate by parts (22.6.6) at a general t>0t>0 to show that Γ(t+1)=t Γ(t)\Gamma(t+1)=t\,\Gamma(t), and conclude that Γ(n+1)=n!\Gamma(n+1)=n! for every integer n≥0n\ge 0. Where does the argument use t>0t>0? Use the result to compute the variance of the exponential density e−ue^{-u} on u≥0u\ge 0, whose mean we computed in Section 22.6.2.3.
    3. Substitute u=x2u=x^2 and use the Gaussian integral (22.6.13) to evaluate Γ(12)\Gamma(\tfrac12).
    4. The product rule (22.6.10), applied dd times, gives ∫Rde−∥x∥2 dx=πd/2\int_{\mathbb R^d}e^{-\|\mathbf x\|^2}\,d\mathbf x=\pi^{d/2}. In polar form the same integral is Sd−1∫0∞rd−1e−r2 drS_{d-1}\int_0^\infty r^{d-1}e^{-r^2}\,dr, where Sd−1S_{d-1} is the surface area of the unit sphere in Rd\mathbb R^d. Show that the radial integral is 12Γ(d/2)\tfrac12\Gamma(d/2) and deduce Sd−1=2πd/2/Γ(d/2)S_{d-1}=2\pi^{d/2}/\Gamma(d/2). Integrate Sd−1rd−1S_{d-1}r^{d-1} over r∈[0,1]r\in[0,1] to show that the unit ball has volume Vd=πd/2/Γ(d/2+1)V_d=\pi^{d/2}/\Gamma(d/2+1). Evaluate VdV_d for d∈{1,2,3,5,10,20}d\in\{1,2,3,5,10,20\} and explain why Vd→0V_d\to0. A midpoint grid with three points per axis on the cube [−1,1]10[-1,1]^{10} has 3103^{10} points; what fraction of them lies inside the unit ball, and what does that say about grids in high dimensions?
  4. Swapping the order. Fubini's theorem (22.6.9), together with zero-extension for regions that are not rectangles, lets us choose the order of integration.

    1. The inner integral of ∫01(∫y1e−x2 dx) dy\int_0^1\bigl(\int_y^1 e^{-x^2}\,dx\bigr)\,dy has no elementary antiderivative. Sketch the triangular region of integration, reverse the order, and evaluate the integral in closed form.
    2. Let X≥0X\ge 0 have density pp. Write x=∫0xdtx=\int_0^x dt inside E[X]=∫0∞x p(x) dx\mathbb{E}[X]=\int_0^\infty x\,p(x)\,dx and swap the two integrals to show that E[X]=∫0∞P(X>t) dt\mathbb{E}[X]=\int_0^\infty P(X>t)\,dt. Why is the swap valid even when E[X]=∞\mathbb{E}[X]=\infty? Check the formula on the density λe−λx\lambda e^{-\lambda x} for x≥0x\ge 0.
  5. Gaussian normalizers and moments. The text normalizes the standard normal and computes its moments with the Stein identity (22.6.7) for the bell weight. Let p(x)=12πσ2exp⁡(−(x−μ)22σ2)p(x)=\tfrac{1}{\sqrt{2\pi\sigma^2}}\exp\bigl(-\tfrac{(x-\mu)^2}{2\sigma^2}\bigr) with σ>0\sigma>0.

    1. Substitute x=μ+σzx=\mu+\sigma z and use (22.6.14) to show that pp is normalized. Which μ\mu and σ2\sigma^2 does the density 1πe−x2\tfrac{1}{\sqrt\pi}e^{-x^2} have?
    2. Let XX have density pp, and let gg be continuously differentiable with g(x) p(x)→0g(x)\,p(x)\to 0 as x→±∞x\to\pm\infty. Use p′(x)=−x−μσ2 p(x)p'(x)=-\tfrac{x-\mu}{\sigma^2}\,p(x) and integration by parts to show that
E[(X−μ) g(X)]=σ2 E[g′(X)].(22.6.15)\mathbb{E}\bigl[(X-\mu)\,g(X)\bigr]=\sigma^2\,\mathbb{E}\bigl[g'(X)\bigr]. \tag{22.6.15}

Deduce that E[(X−μ)2]=σ2\mathbb{E}[(X-\mu)^2]=\sigma^2 and E[(X−μ)4]=3σ4\mathbb{E}[(X-\mu)^4]=3\sigma^4.

  1. Let Σ=LL⊤\boldsymbol\Sigma=\mathbf L\mathbf L^\top be a d×dd\times d covariance matrix with invertible L\mathbf L. Use the change of variables x=Lz\mathbf x=\mathbf L\mathbf z in (22.6.11) and the product rule (22.6.10) to show that
∫Rdexp⁡(−12x⊤Σ−1x) dx=(2π)d/2 (det⁡Σ)1/2.(22.6.16)\int_{\mathbb R^d}\exp\bigl(-\tfrac12\mathbf x^\top\boldsymbol\Sigma^{-1}\mathbf x\bigr)\,d\mathbf x=(2\pi)^{d/2}\,(\det\boldsymbol\Sigma)^{1/2}. \tag{22.6.16}

Discussions