Module contents
Lesson 11 of 20Core 110 min

Multiple integrals and change of variables

Integration in ℝⁿ: iterated integrals and Fubini's theorem, change of variables with the absolute Jacobian determinant, polar and spherical coordinates, the Gaussian integral in any dimension, the volume of the n-dimensional ball and differentiation under the integral sign. These are the mathematical foundations of density transformations, normalizing flows and reparameterized gradient estimators.

After this lesson you can

  • Compute multiple integrals by iteration and justify exchanging integration order with Fubini and Tonelli.
  • Prove and apply the change-of-variables formula with |det J| and obtain the density of a transformed variable.
  • Compute the Gaussian integral and the normalization constant of a multivariate Gaussian.
  • Derive the unit ball volume in ℝⁿ and explain concentration of volume near the boundary.
  • Apply Leibniz's rule for differentiation under the integral sign and verify its hypotheses.

Before you start

Motivation: integration in several variables

Almost everything making high-dimensional probability useful is a multiple integral, and almost everything breaking in high dimensions breaks because of one. Three concrete tasks recurring throughout the course show why they must be mastered.

  • Normalize a density. A multivariate Gaussian is proportional to exp⁡ ⁣(−12(x−μ)⊤Σ−1(x−μ))\exp\!\big(-\tfrac12(\vb{x}-\vb{\mu})\T\mat{\Sigma}\inv(\vb{x}-\vb{\mu})\big). To make it a density, divide by its integral over Rn\R^n, and that constant, (2π)n/2det⁡(Σ)1/2(2\pi)^{n/2}\det(\mat{\Sigma})^{1/2}, is not a matter of taste: it appears in every likelihood, KL between Gaussians and Bayesian update.
  • Calculate expectations. E[g(X)]=∫g(x) p(x) ⁣dx\E[g(\vb{X})] = \int g(\vb{x})\,p(\vb{x})\dd\vb{x}. An expectation is an integral with respect to a density, and when X\vb{X} has nn components it is a multiple integral. Understanding its calculation (and why grid quadrature does not scale) is the reason for Monte Carlo.
  • Transform random variables. If Y=f(X)\vb{Y} = f(\vb{X}), what density does Y\vb{Y} have? The answer, with absolute Jacobian determinant, is the change-of-variables formula for densities. It generates a Gaussian from two uniforms (Box–Muller) and trains normalizing flows, maximizing a likelihood with central term log⁡∣det⁡J∣\log\abs{\det J}.

There are also two unexpected gifts from an integration lesson. One is geometric: the unit-ball volume of Rn\R^n tends to zero as nn grows, and almost all that volume lives in a shell against the boundary, destroying our intuition for distances and neighborhoods. The other is analytic: Leibniz’s rule, allowing differentiation under the integral sign, justifies the reparameterization trick used to train variational autoencoders (VAEs).

The lesson follows this order: multiple integrals and Fubini’s theorem reducing them to single-variable integrals; change of variables and classic cases (polar, spherical); the Gaussian integral and nn-dimensional ball, combining the preceding material; Leibniz’s rule; and density transformation with applications. All relies on the Riemann integral and fundamental theorem of calculus from lesson 2, and the Jacobian determinant from lesson 7.

The multiple integral: Riemann sums on a rectangle

The definition is the single-variable one with intervals replaced by rectangles. Let Q=[a1,b1]×⋯×[an,bn]⊂RnQ = [a_1, b_1] \times \cdots \times [a_n, b_n] \subset \R^n be a closed rectangle of volume vol⁡(Q)=∏i(bi−ai)\operatorname{vol}(Q) = \prod_i (b_i - a_i). Partition each edge [ai,bi][a_i, b_i] into subintervals; products of one subinterval from each edge are rectangles R1,…,RNR_1, \dots, R_N covering QQ and touching only at boundaries. This is a partition PP. For a bounded function f:Q→Rf : Q \to \R define, as in lesson 2, lower and upper Darboux sums:

L(f,P)=∑j=1Nmjvol⁡(Rj),U(f,P)=∑j=1NMjvol⁡(Rj),mj=inf⁡Rjf,Mj=sup⁡Rjf.L(f, P) = \sum_{j=1}^N m_j \operatorname{vol}(R_j), \qquad U(f, P) = \sum_{j=1}^N M_j \operatorname{vol}(R_j), \qquad m_j = \inf_{R_j} f, \quad M_j = \sup_{R_j} f.

With n=2n = 2 and f≥0f \ge 0, ∬Ωf\iint_\Omega f is the volume of the solid between Ω\Omega and the graph of ff. With f=1f = 1 we obtain volume (or area) of Ω\Omega. With density pp instead of ff, we obtain probability of Ω\Omega.

The first question is when it exists. In one variable continuous functions are integrable because uniformly continuous on a compact set; the argument survives intact.

Proof

QQ is compact, so ff is uniformly continuous: given ε>0\eps > 0 there exists δ>0\delta > 0 such that ∣f(x)−f(y)∣<ε\abs{f(\vb{x}) - f(\vb{y})} < \eps whenever ∥x−y∥<δ\norm{\vb{x} - \vb{y}} < \delta. Take a partition whose rectangles all have diameter less than δ\delta. On each RjR_j (compact), ff attains maximum and minimum, whose difference is less than ε\eps. Hence Mj−mj<εM_j - m_j < \eps and

U(f,P)−L(f,P)=∑j(Mj−mj)vol⁡(Rj)≤εvol⁡(Q).U(f, P) - L(f, P) = \sum_j (M_j - m_j)\operatorname{vol}(R_j) \le \eps \operatorname{vol}(Q).

Since ε\eps is arbitrary, the supremum of lower sums and infimum of upper sums agree.

∎

This is insufficient to integrate over a ball or triangle, because extending ff by zero makes the integrand jump on boundary Ω\Omega. Lebesgue’s criterion covers everything. A set Z⊂RnZ \subset \R^n has measure zero if for each ε>0\eps > 0 it can be covered by countably many rectangles of total volume less than ε\eps. Finite or countable sets, segments and graphs of continuous functions y=φ(x)y = \varphi(x) in R2\R^2 have measure zero.

(The proof is in Hubbard and Hubbard, chapter 4.) An immediate consequence: if ff is continuous and bounded on bounded set Ω\Omega whose boundary has measure zero (a ball, polygon, region between continuous graphs), then f 1Ωf\,\ind_\Omega is discontinuous only on ∂Ω\partial\Omega and ∫Ωf\int_\Omega f exists. These are our working domains. A function like 1[x∈Q2]\ind[\vb{x} \in \mathbb{Q}^2] fails the criterion: it is discontinuous everywhere and not Riemann integrable (it is Lebesgue integrable, seen in measure theory in the probability module).

The multiple integral inherits expected properties: linearity in ff, monotonicity (f≤gf \le g implies ∫f≤∫g\int f \le \int g), ∣∫f∣≤∫∣f∣\abs{\int f} \le \int \abs{f}, and domain additivity, ∫Ω1∪Ω2f=∫Ω1f+∫Ω2f\int_{\Omega_1 \cup \Omega_2} f = \int_{\Omega_1} f + \int_{\Omega_2} f if the two sets overlap only on a measure-zero set. What it does not inherit is a calculation method: summing thousands of rectangles is not an option, so the next theorem is needed.

Iterated integrals and Fubini’s theorem

To calculate a solid’s volume, slice it. Plane x=cx = c cuts the solid and its cross-sectional area A(c)=∫f(c,y) ⁣dyA(c) = \int f(c, y) \dd y is measured; volume is the sum (integral) of those areas along xx. This is an iterated integral, ∫(∫f(x,y) ⁣dy) ⁣dx\int \big(\int f(x, y) \dd y\big) \dd x. The natural question is whether the result depends on slicing direction and agrees with the double integral.

InteractiveSlicing a volume
Section area as a function of cc: the area under the curve is the volume
A(x)
  • cutting plane and section
  • accumulated volume
Surface z=f(x,y)z = f(x, y)
Integration region
Slice with planes
0.40
Section area, A(c)A(c)0.9467
Volume accumulated up to cc0.2696
Total slicing along xx0.7329
Total slicing along yy0.7329
Both orders give the same volume: ff is continuous on a compact set, so ∬∣f∣\iint\abs{f} is finite and Fubini applies.
A plane slices the solid under the surface. Each section's area accumulates in the graph on the right, and the area under that curve is volume. Slice in xx then yy and compare totals. With triangle y≤xy \le x notice each section's bounds change with cc: changing order forces recalculation. With counterexample (x2−y2)/(x2+y2)2(x^2 - y^2)/(x^2 + y^2)^2 the totals differ: which assumption fails?

The result says that under reasonable assumptions slicing in any order agrees. It is called Fubini’s theorem; start with its classical form for continuous functions, proved with Darboux sums.

Proof

Continuity of FF follows from uniform continuity: if ∣x−x′∣<δ\abs{x - x'} < \delta then ∣f(x,y)−f(x′,y)∣<ε\abs{f(x, y) - f(x', y)} < \eps for every yy, hence ∣F(x)−F(x′)∣≤ε(d−c)\abs{F(x) - F(x')} \le \eps(d - c). Equality remains. Take partitions a=x0<⋯<xp=ba = x_0 < \cdots < x_p = b and c=y0<⋯<yq=dc = y_0 < \cdots < y_q = d, with mijm_{ij} and MijM_{ij} the minimum and maximum of ff on Rij=[xi−1,xi]×[yj−1,yj]R_{ij} = [x_{i-1}, x_i] \times [y_{j-1}, y_j]. For x∈[xi−1,xi]x \in [x_{i-1}, x_i] and each jj, mij≤f(x,y)≤Mijm_{ij} \le f(x, y) \le M_{ij} for every y∈[yj−1,yj]y \in [y_{j-1}, y_j]; integrate in yy and sum in jj,

∑jmij Δyj  ≤  F(x)  ≤  ∑jMij Δyj.\sum_j m_{ij}\,\Delta y_j \;\le\; F(x) \;\le\; \sum_j M_{ij}\,\Delta y_j .

The bound holds for every xx in the interval, so also bounds infimum and supremum of FF there. Multiply by Δxi\Delta x_i and sum in ii to get L(f,P)≤L(F,Px)≤U(F,Px)≤U(f,P)L(f, P) \le L(F, P_x) \le U(F, P_x) \le U(f, P). Since ff is integrable, L(f,P)L(f, P) and U(f,P)U(f, P) approach ∬f\iint f as PP is refined, and the chain forces ∫abF=∬f\int_a^b F = \iint f. The other order is identical.

∎

For nonrectangular domains, an elementary region lies between two graphs, Ω={(x,y):a≤x≤b, φ1(x)≤y≤φ2(x)}\Omega = \{(x, y) : a \le x \le b,\ \varphi_1(x) \le y \le \varphi_2(x)\} with φ1≤φ2\varphi_1 \le \varphi_2 continuous, and then ∬Ωf=∫ab∫φ1(x)φ2(x)f(x,y) ⁣dy ⁣dx\iint_\Omega f = \int_a^b \int_{\varphi_1(x)}^{\varphi_2(x)} f(x, y) \dd y \dd x. Changing order requires rewriting bounds describing the same region as c≤y≤dc \le y \le d, ψ1(y)≤x≤ψ2(y)\psi_1(y) \le x \le \psi_2(y).

Tonelli, Fubini and the counterexample

The preceding theorem suffices for continuous functions on compact sets. Probability requires integration over all Rn\R^n of functions that are not continuous, and the general version is as follows (for the Lebesgue integral; its proof appears in any measure-theory text and the probability module).

They are used together: to justify an order interchange first apply Tonelli to ∣f∣\abs{f} (always possible) and check the result is finite; then Fubini to ff. Absolute integrability is not a technical luxury, as the following example, not covered by Fubini, demonstrates.

The square counterexample has a practical lesson. If a neighborhood of the origin is removed, [δ,1]2[\delta, 1]^2 with δ>0\delta > 0, ff is continuous and Fubini applies; by antisymmetry the integral is exactly 00. And symmetric quadrature on [0,1]2[0, 1]^2 also gives 00 (seen below): neither π/4\pi/4 nor −π/4-\pi/4, but a third number without meaning. Interchanging order without checking absolute integrability is an unproved assertion.

Change of variables

In one variable substitution x=φ(u)x = \varphi(u) gives ∫φ(a)φ(b)f(x) ⁣dx=∫abf(φ(u)) φ′(u) ⁣du\int_{\varphi(a)}^{\varphi(b)} f(x) \dd x = \int_a^b f(\varphi(u))\,\varphi'(u) \dd u. In several variables the Jacobian determinant takes the role of φ′\varphi', and an absolute value appears that in one variable is hidden in bound orientation.

The geometry is from lesson 7. A differentiable map φ\varphi, magnified near point u0\vb{u}_0, is its linearization φ(u0+h)≈φ(u0)+Jφ(u0) h\varphi(\vb{u}_0 + \vb{h}) \approx \varphi(\vb{u}_0) + J_\varphi(\vb{u}_0)\,\vb{h}. A linear matrix A\mat{A} turns any cube into a parallelepiped of ∣det⁡A∣\abs{\det\mat{A}} times the volume (determinant as volume factor). Thus a tiny cell of volume  ⁣du\dd\vb{u} occupies volume ∣det⁡Jφ(u0)∣ ⁣du\abs{\det J_\varphi(\vb{u}_0)}\dd\vb{u}, and summing ff on image cells equals summing f(φ(u))f(\varphi(\vb{u})) times each cell’s scale factor.

Proof

Sketch, with the two conceptual steps. (1) Linear case. For φ(u)=Au\varphi(\vb{u}) = \mat{A}\vb{u}, the image of rectangle RR is a parallelepiped of volume ∣det⁡A∣vol⁡(R)\abs{\det\mat{A}}\operatorname{vol}(R), the determinant as volume (linear algebra lesson 6); with step function ff the formula sums that equality. (2) Local case. Let CC be a cube of side δ\delta and center u0\vb{u}_0, with J=Jφ(u0)J = J_\varphi(\vb{u}_0). By uniform differentiability on a compact set, φ(u)=φ(u0)+J(u−u0)+r(u)\varphi(\vb{u}) = \varphi(\vb{u}_0) + J(\vb{u} - \vb{u}_0) + \vb{r}(\vb{u}) with ∥r(u)∥≤ε δ\norm{\vb{r}(\vb{u})} \le \eps\,\delta for small δ\delta. Then φ(u)−φ(u0)=J(u−u0+J−1r)\varphi(\vb{u}) - \varphi(\vb{u}_0) = J\big(\vb{u} - \vb{u}_0 + J\inv\vb{r}\big) and ∥J−1r∥≤ε ∥J−1∥ δ\norm{J\inv\vb{r}} \le \eps\,\norm{J\inv}\,\delta: the image of CC lies inside the image under JJ of a slightly larger cube, with volume at most (1+η)∣det⁡J∣δn(1 + \eta)\abs{\det J}\delta^n, with η→0\eta \to 0 as ε→0\eps \to 0. Sum over cells of a compact-set partition and take limits to obtain vol⁡(φ(Ω))≤∫Ω∣det⁡Jφ∣\operatorname{vol}(\varphi(\Omega)) \le \int_\Omega \abs{\det J_\varphi}. Applying the same to φ−1\varphi\inv gives the reverse inequality, yielding equality for f=1φ(Ω)f = \ind_{\varphi(\Omega)}, then for step functions and, by approximation, integrable ff.

∎

Absolute value is essential because a volume integral cannot be negative: if φ\varphi reverses orientation (like (u,v)↦(v,u)(u, v) \mapsto (v, u)) its determinant is negative, while the image region still has positive volume.

From the formula to densities

Now take a random variable X∈Rn\vb{X} \in \R^n with density pXp_X, and transformation Y=f(X)\vb{Y} = f(\vb{X}) with ff a diffeomorphism. For any set BB,

P(Y∈B)=P(X∈f−1(B))=∫f−1(B)pX(x) ⁣dx=∫BpX(f−1(y)) ∣det⁡Jf−1(y)∣ ⁣dy,\Pr(\vb{Y} \in B) = \Pr\big(\vb{X} \in f\inv(B)\big) = \int_{f\inv(B)} p_X(\vb{x}) \dd\vb{x} = \int_B p_X\big(f\inv(\vb{y})\big)\,\abs{\det J_{f\inv}(\vb{y})} \dd\vb{y},

where the last step substitutes x=f−1(y)\vb{x} = f\inv(\vb{y}) using the change of variables above (with φ=f−1\varphi = f\inv). Since this holds for every BB, the integrand is the density of Y\vb{Y}.

Both forms are the same because Jf−1(y)=Jf(x)−1J_{f\inv}(\vb{y}) = J_f(\vb{x})\inv (chain rule applied to f−1∘f=id⁡f\inv \circ f = \operatorname{id}) and det⁡(A−1)=1/det⁡A\det(\mat{A}\inv) = 1/\det\mat{A}. In logarithms, as used in practice,

log⁡pY(y)=log⁡pX(f−1(y))+log⁡∣det⁡Jf−1(y)∣=log⁡pX(x)−log⁡∣det⁡Jf(x)∣.\log p_Y(\vb{y}) = \log p_X\big(f\inv(\vb{y})\big) + \log\abs{\det J_{f\inv}(\vb{y})} = \log p_X(\vb{x}) - \log\abs{\det J_f(\vb{x})}.

The next interactive shows both sides at once: cells stretching or compressing according to ∣det⁡J∣\abs{\det J}, and a sample histogram confirming the formula.

InteractivePushing a density through a change of variables
Base (r,θ)(r, \theta): uniform grid and samples
Image y=f(x)\vb{y} = f(\vb{x}): cells colored by ∣det⁡Jf∣\abs{\det J_f}
2D histogram of the NN transported samples
Density predicted by the chosen formula
correcta
  • cells by ∣det⁡Jf∣\abs{\det J_f} (darker means more area)
  • chosen cell
  • samples and histogram
Choosing uniform rr and θ\theta in (0,1]×[0,2π)(0,1] \times [0,2\pi) does not yield uniform points in the disk: a cell has area r  ⁣dr  ⁣dθr\,\dd r\,\dd\theta, so near the center the same base cell covers very little area.
Density formula
12000
Base cell area0.0491
Area of its image0.0153
Image / base ratio0.312
∣det⁡Jf∣\abs{\det J_f} at the center0.313
∫\int of prediction1.00
Distance ½‖hist − prediction‖₁0.055
Distance: correct · no det. · direct0.06 · 0.26 · 0.34
pY(y)=pX(f−1(y)) ∣det⁡Jf−1(y)∣p_Y(\vb{y}) = p_X(f^{-1}(\vb{y}))\,\abs{\det J_{f^{-1}}(\vb{y})}: the correct formula.
Above, a uniform base grid and its image, each cell colored by ∣det⁡Jf∣\abs{\det J_f}. Drag the base-grid point to choose a cell and compare its image area with the determinant at its center. Below, the 2D histogram of thousands of transported samples alongside the density predicted by the chosen formula. With polar coordinates: why do samples crowd the center? With ‘without determinant’: what does the prediction integrate to? Try the forward Jacobian in the affine transform and coupling: when does it match the inverse one?

Three things to take from the interactive. First, the correct formula alone integrates to 1: without the determinant predicted mass differs from 1 because a density is mass per unit volume and ff changes volume units. Second, using forward Jacobian ∣det⁡Jf∣\abs{\det J_f} instead of the inverse multiplies ∣det⁡Jf∣2\abs{\det J_f}^2 what should be pX/∣det⁡Jf∣p_X/\abs{\det J_f}; harmless only when the determinant equals ±1\pm 1. Third, a constant determinant (affine) stretches all cells equally, so a Gaussian remains Gaussian, while a variable one (polar, Box–Muller, coupling) redistributes mass.

Polar, cylindrical and spherical coordinates

The most-used changes of variables adapt integration to domain symmetry. These three systems of polar, cylindrical and spherical coordinates have Jacobians calculable mentally.

Polar in R2\R^2: x=rcos⁡θx = r\cos\theta, y=rsin⁡θy = r\sin\theta with r>0r > 0 and θ∈[0,2π)\theta \in [0, 2\pi). The Jacobian matrix and determinant are

J=[cos⁡θ−rsin⁡θsin⁡θrcos⁡θ],det⁡J=rcos⁡2θ+rsin⁡2θ=r, ⁣dx ⁣dy=r ⁣dr ⁣dθ.J = \begin{bmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{bmatrix}, \qquad \det J = r\cos^2\theta + r\sin^2\theta = r, \qquad \dd x \dd y = r \dd r \dd\theta.

Cylindrical in R3\R^3: polar plus height zz, with  ⁣dx ⁣dy ⁣dz=r ⁣dr ⁣dθ ⁣dz\dd x\dd y\dd z = r \dd r \dd\theta \dd z.

Spherical in R3\R^3, with ρ≥0\rho \ge 0, colatitude φ∈[0,π]\varphi \in [0, \pi] (angle with axis zz) and θ∈[0,2π)\theta \in [0, 2\pi): x=ρsin⁡φcos⁡θx = \rho\sin\varphi\cos\theta, y=ρsin⁡φsin⁡θy = \rho\sin\varphi\sin\theta, z=ρcos⁡φz = \rho\cos\varphi. The three columns of JJ are

∂ρ=[sin⁡φcos⁡θsin⁡φsin⁡θcos⁡φ],∂φ=ρ[cos⁡φcos⁡θcos⁡φsin⁡θ−sin⁡φ],∂θ=ρsin⁡φ[−sin⁡θcos⁡θ0].\partial_\rho = \begin{bmatrix} \sin\varphi\cos\theta \\ \sin\varphi\sin\theta \\ \cos\varphi \end{bmatrix}, \quad \partial_\varphi = \rho\begin{bmatrix} \cos\varphi\cos\theta \\ \cos\varphi\sin\theta \\ -\sin\varphi \end{bmatrix}, \quad \partial_\theta = \rho\sin\varphi\begin{bmatrix} -\sin\theta \\ \cos\theta \\ 0 \end{bmatrix}.

They are pairwise orthogonal (check dot products) and their lengths are 11, ρ\rho and ρsin⁡φ\rho\sin\varphi. For a matrix of orthogonal columns, J⊤J\mat{J}\T\mat{J} is diagonal with squared lengths, and ∣det⁡J∣=det⁡(J⊤J)\abs{\det J} = \sqrt{\det(\mat{J}\T\mat{J})} is their product:

∣det⁡J∣=ρ2sin⁡φ, ⁣dx ⁣dy ⁣dz=ρ2sin⁡φ ⁣dρ ⁣dφ ⁣dθ.\abs{\det J} = \rho^2\sin\varphi, \qquad \dd x \dd y \dd z = \rho^2\sin\varphi \dd\rho \dd\varphi \dd\theta.

Geometrically, a spherical cell is nearly a box with sides  ⁣dρ\dd\rho, ρ ⁣dφ\rho\dd\varphi and ρsin⁡φ ⁣dθ\rho\sin\varphi\dd\theta, explaining each factor. With φ∈[0,π]\varphi \in [0, \pi], sin⁡φ≥0\sin\varphi \ge 0 and no absolute value is needed. The origin (polar), axis r=0r = 0 (cylindrical) and axis zz, where sin⁡φ=0\sin\varphi = 0 (spherical), are measure-zero sets where the map ceases to be injective or its Jacobian vanishes, as is half-plane or ray θ=0\theta = 0 where angle endpoints meet; the formula still holds.

In dimension nn there is no need to construct general spherical coordinates. For radial integrands, f(x)=h(∥x∥)f(\vb{x}) = h(\norm{\vb{x}}), scaling suffices: ball {∥x∥≤r}\{\norm{\vb{x}} \le r\} has volume VnrnV_n r^n because x↦rx\vb{x} \mapsto r\vb{x} multiplies volumes by ∣det⁡(rI)∣=rn\abs{\det(r\mat{I})} = r^n. The shell between radii ri−1r_{i-1} and rir_i has volume Vn(rin−ri−1n)V_n(r_i^n - r_{i-1}^n), and a Riemann–Stieltjes sum with respect to r↦Vnrnr \mapsto V_n r^n gives the result.

(This is a Riemann–Stieltjes integral, from lesson 2, with respect to r↦Vnrnr \mapsto V_n r^n, whose derivative is nVnrn−1nV_n r^{n-1}.) With n=2n = 2 polar factor 2πr2\pi r reappears, and with n=3n = 3, 4πr24\pi r^2.

The Gaussian integral

Function e−x2e^{-x^2} has no elementary antiderivative, yet its integral over the entire line, an improper integral, equals exactly π\sqrt\pi. The proof, Poisson’s trick, is the best example of what change of variables buys: move to two dimensions to solve a one-dimensional problem.

Proof

Let IR=∫−RRe−x2 ⁣dxI_R = \int_{-R}^R e^{-x^2}\dd x. By Fubini (the integrand is continuous on a rectangle), IR2=∬[−R,R]2e−(x2+y2) ⁣dx ⁣dyI_R^2 = \iint_{[-R,R]^2} e^{-(x^2+y^2)}\dd x\dd y. Disk DRD_R of radius RR lies inside the square, and the square inside disk DR2D_{R\sqrt 2}. Since the integrand is positive,

∬DRe−(x2+y2)  ≤  IR2  ≤  ∬DR2e−(x2+y2).\iint_{D_R} e^{-(x^2+y^2)} \;\le\; I_R^2 \;\le\; \iint_{D_{R\sqrt2}} e^{-(x^2+y^2)}.

In polar coordinates, ∬DRe−(x2+y2) ⁣dx ⁣dy=∫02π ⁣∫0Re−r2 r ⁣dr ⁣dθ=π(1−e−R2)\iint_{D_R} e^{-(x^2+y^2)}\dd x\dd y = \int_0^{2\pi}\!\int_0^R e^{-r^2}\,r\dd r\dd\theta = \pi\big(1 - e^{-R^2}\big), because r e−r2r\,e^{-r^2} does have an antiderivative, −12e−r2-\tfrac12 e^{-r^2}. Therefore

π(1−e−R2)≤IR2≤π(1−e−2R2),\pi\big(1 - e^{-R^2}\big) \le I_R^2 \le \pi\big(1 - e^{-2R^2}\big),

and as R→∞R \to \infty both bounds tend to π\pi: IR→πI_R \to \sqrt\pi.

∎

Factor rr in r ⁣dr ⁣dθr\dd r\dd\theta turns an integral with no antiderivative into one with one: without the Jacobian, ∫e−r2 ⁣dr\int e^{-r^2}\dd r would still be impossible. The figure makes this visible. Rings of thickness  ⁣dr\dd r have area 2πr ⁣dr2\pi r\dd r, and unrolling them shows why: the strip at radius rr is 2πr2\pi r long.

InteractivePoisson's trick
The rings of e−(x2+y2)e^{-(x^2 + y^2)} and their unrolling
cuadradodisco circunscrito
Volume of each ring: bars below 2πr e−r22\pi r\,e^{-r^2}
R2πr e^(−r²)
  • rings (darker where e−r2e^{-r^2} is greater)
  • chosen ring
  • 2πr e−r22\pi r\,e^{-r^2}
1.80
14
r ≈ 0.84
0.00
Ring area, 2πr  ⁣dr2\pi r\,\dd r0.6751
Ring volume, e−r2 2πr  ⁣dre^{-r^2}\,2\pi r\,\dd r0.3358
Sum of the rings3.02382
π (1−e−R2)\pi\,(1 - e^{-R^2}), the disk3.01856
π erf(R)2\pi\,\mathrm{erf}(R)^2, the square [−R,R]2[-R, R]^23.07342
π (1−e−2R2)\pi\,(1 - e^{-2R^2}), the circumscribed disk3.13677
Limit R→∞R \to \infty3.14159
The square lies between two disks, and both disks tend to π\pi: therefore (∫e−x2 ⁣dx)2=π\left(\int e^{-x^2}\dd x\right)^2 = \pi.
On the left, disk of radius RR cut into rings; press ‘Unroll’ and pause anywhere: each ring opens into a strip of length proportional to rr (to fit, the figure is not to scale: the strip of radius rr is drawn with height 2r2r instead of 2πr2\pi r and twice as wide, but strip proportions are preserved). At zero unrolling, square [−R,R]2[-R, R]^2 is visible between the disk and circumscribed disk. On the right, volume of each ring, e−r2 2πr  ⁣dre^{-r^2}\,2\pi r\,\dd r, as a bar under curve 2πr e−r22\pi r\,e^{-r^2}. Raise RR and watch the readouts: π erf(R)2\pi\,\mathrm{erf}(R)^2 always lies between the other two and all tend to π\pi. How many rings make the Riemann sum match the exact integral to four digits?

From the one-dimensional integral, scaling and translation give normalization constants for all scalar Gaussians: ∫e−(x−μ)2/(2σ2) ⁣dx=σ2π\int e^{-(x-\mu)^2/(2\sigma^2)}\dd x = \sigma\sqrt{2\pi}. And from Gamma: with t=x2t = x^2, Γ(12)=∫0∞t−1/2e−t ⁣dt=2∫0∞e−x2 ⁣dx=π\Gamma(\tfrac12) = \int_0^\infty t^{-1/2}e^{-t}\dd t = 2\int_0^\infty e^{-x^2}\dd x = \sqrt\pi, a value of the Gamma function used shortly.

The multivariate Gaussian

For the multivariate case we need two linear-algebra ingredients. A symmetric positive-definite matrix Σ\mat{\Sigma} diagonalizes in an orthonormal basis by the spectral theorem, Σ=QΛQ⊤\mat{\Sigma} = \mat{Q}\mat{\Lambda}\mat{Q}\T with Q\mat{Q} orthogonal and Λ=diag⁡(λ1,…,λn)\mat{\Lambda} = \diag(\lambda_1, \dots, \lambda_n), λi>0\lambda_i > 0. And a linear substitution has its matrix as Jacobian.

Proof

Translation x↦x−μ\vb{x} \mapsto \vb{x} - \vb{\mu} has Jacobian 1. Set x−μ=QΛ1/2z\vb{x} - \vb{\mu} = \mat{Q}\mat{\Lambda}^{1/2}\vb{z}, with Jacobian QΛ1/2\mat{Q}\mat{\Lambda}^{1/2} and ∣det⁡∣=det⁡(Λ)1/2=det⁡(Σ)1/2\abs{\det} = \det(\mat{\Lambda})^{1/2} = \det(\mat{\Sigma})^{1/2}, because Q\mat{Q} is orthogonal and det⁡Σ=∏iλi\det\mat{\Sigma} = \prod_i\lambda_i. The exponent becomes z⊤Λ1/2Q⊤QΛ−1Q⊤QΛ1/2z=∥z∥2\vb{z}\T\mat{\Lambda}^{1/2}\mat{Q}\T\mat{Q}\mat{\Lambda}\inv\mat{Q}\T\mat{Q}\mat{\Lambda}^{1/2}\vb{z} = \norm{\vb{z}}^2. The integral becomes det⁡(Σ)1/2∫Rne−∥z∥2/2 ⁣dz\det(\mat{\Sigma})^{1/2}\int_{\R^n} e^{-\norm{\vb{z}}^2/2}\dd\vb{z}, and by Tonelli (the integrand is positive) that integral is the product of nn one-dimensional integrals ∫e−zi2/2 ⁣dzi=2π\int e^{-z_i^2/2}\dd z_i = \sqrt{2\pi}. The second form follows from Σ−1=2A\mat{\Sigma}\inv = 2\mat{A}, with det⁡Σ=2−ndet⁡(A)−1\det\mat{\Sigma} = 2^{-n}\det(\mat{A})^{-1}.

∎

Thus the density of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}) is (2π)−n/2det⁡(Σ)−1/2exp⁡(⋯ )(2\pi)^{-n/2}\det(\mat{\Sigma})^{-1/2}\exp(\cdots), the formula stated in the multivariate Gaussian definition and previously obtained differently in the affine-transformation example. Notice each assumption’s role: positive definiteness guarantees λi>0\lambda_i > 0 (a negative eigenvalue makes the exponent grow without bound in its direction and the integral diverge; with a zero eigenvalue Σ\mat{\Sigma} has no inverse), and the spectral theorem gives the rotation decoupling variables.

Ball volume in Rn\R^n

The Gaussian integral just calculated in R\R can also be calculated in Rn\R^n in two ways. Factoring gives ∫Rne−∥x∥2 ⁣dx=(π)n=πn/2\int_{\R^n} e^{-\norm{\vb{x}}^2}\dd\vb{x} = \big(\sqrt\pi\big)^n = \pi^{n/2}. With radial integration,

∫Rne−∥x∥2 ⁣dx=nVn∫0∞e−r2rn−1 ⁣dr=nVn⋅12 Γ ⁣(n2)=Vn Γ ⁣(n2+1),\int_{\R^n} e^{-\norm{\vb{x}}^2}\dd\vb{x} = n V_n\int_0^\infty e^{-r^2} r^{n-1}\dd r = n V_n \cdot \frac12\,\Gamma\!\Big(\frac n2\Big) = V_n\,\Gamma\!\Big(\frac n2 + 1\Big),

where t=r2t = r^2 recognizes ∫0∞rn−1e−r2 ⁣dr=12Γ(n/2)\int_0^\infty r^{n-1}e^{-r^2}\dd r = \tfrac12\Gamma(n/2) and Γ(s+1)=sΓ(s)\Gamma(s + 1) = s\Gamma(s) was used. Equating both expressions yields unit-ball volume:

Vn=πn/2Γ ⁣(n2+1),Sn−1=nVn=2πn/2Γ ⁣(n2).V_n = \frac{\pi^{n/2}}{\Gamma\!\big(\tfrac n2 + 1\big)}, \qquad S_{n-1} = nV_n = \frac{2\pi^{n/2}}{\Gamma\!\big(\tfrac n2\big)}.

With n=1,2,3n = 1, 2, 3 we recover 22, π\pi and 4π/34\pi/3. Relation Γ(s+1)=s Γ(s)\Gamma(s+1) = s\,\Gamma(s) also gives recurrence Vn=2πnVn−2V_n = \dfrac{2\pi}{n}V_{n-2}, and with it nearly the whole story: VnV_n exceeds Vn−2V_{n-2} only while 2π/n>12\pi/n > 1, that is, for n≤6n \le 6. Thus the odd subsequence grows to V5V_5 and the even one to V6V_6, then both decrease; since V5≈5.264>V6≈5.168V_5 \approx 5.264 > V_6 \approx 5.168, the maximum of the whole sequence is at n=5n = 5.

nn123456781020
VnV_n23.14164.18884.93485.26385.16774.72484.05872.55020.0258

The maximum is at n=5n = 5 (V5=8π2/15≈5.2638V_5 = 8\pi^2/15 \approx 5.2638), after which volume decreases faster than any exponential: Vn∼(2πe/n)n/2/πnV_n \sim (2\pi e/n)^{n/2}/\sqrt{\pi n}, as follows from Stirling’s formula. In dimension 100100 the unit ball has volume 2.4×10−402.4\times 10^{-40}.

InteractiveThe ball that empties
Radial density of a uniformly sampled point in the ball: n rn−1n\,r^{n-1}
1 − ε = 0.95
Volume Vn=πn/2/Γ(n/2+1)V_n = \pi^{n/2} / \Gamma(n/2 + 1)
  • V_n
  • maximum, n = 5
Fraction of volume in the shell, 1−(1−ε)n1 - (1 - \varepsilon)^n
Fraction of the cube [−1,1]n[-1, 1]^n occupied by the ball, Vn/2nV_n / 2^n
  • shell of thickness ε\varepsilon
  • ball volume
  • ball inside the cube
10
5 %
Scale of VnV_n
Volume VnV_n of the unit ball2.5502
Volume in the shell r>1−εr > 1 - \varepsilon40.13 %
Median radius, 2−1/n2^{-1/n}0.9330
Fraction of the cube [−1,1]n[-1, 1]^n occupied by the ball0.0025
Grid of 10 points per axis1.00e10 evaluations, 1.00e1 s
With ε=0.05\varepsilon = 0.05, the shell contains over 95% of the volume from n=59n = 59.
Increase dimension nn and watch four things at once. Upper left, radial density of a uniform point in the ball, n rn−1n\,r^{n-1}, with shell of thickness ε\varepsilon shaded. Upper right, volume VnV_n: it rises to n=5n = 5 then falls to zero (switch to logarithmic scale to see the plunge). Below, fraction of volume in the shell and fraction of cube [−1,1]n[-1, 1]^n occupied by the ball. With ε=5 %\varepsilon = 5\,\%, from which dimension does the shell contain most of the volume? And 95%? In n=100n = 100, how many evaluations does a grid of 10 points per axis need?

Concentration in the shell

The ball of radius rr has volume VnrnV_n r^n, so the fraction of unit-ball volume within distance 1−ε1 - \eps of the center is (1−ε)n≤e−εn(1 - \eps)^n \le e^{-\eps n}. The fraction in shell {1−ε<∥x∥≤1}\{1 - \eps < \norm{\vb{x}} \le 1\} is its complement:

Vn−Vn(1−ε)nVn=1−(1−ε)n.\frac{V_n - V_n(1 - \eps)^n}{V_n} = 1 - (1 - \eps)^n.

With ε=0.05\eps = 0.05 and n=100n = 100 it is 1−0.95100≈0.9941 - 0.95^{100} \approx 0.994: 99.4 %99.4\,\% of the ball’s volume lies in the outer 5 %5\,\% of its radius. Radial density of a uniform point is n rn−1n\,r^{n-1} on [0,1][0, 1], with median 2−1/n2^{-1/n} (in n=100n = 100, 0.9930.993): a uniform point in a high-dimensional ball is overwhelmingly likely to lie against its surface.

Three consequences used later:

  • Less informative distances. If data are distributed through a region’s volume, almost all lie at the same distance from the center and, by the same argument, from any other point. This degrades nearest neighbors in high dimensions (high-dimensional volume and sphere concentration).
  • The cube is nearly empty inside. The unit ball fits in cube [−1,1]n[-1, 1]^n of volume 2n2^n, and fraction Vn/2nV_n / 2^n is 0.7850.785 in n=2n = 2, 0.00250.0025 in n=10n = 10 and 2.5×10−82.5\times 10^{-8} in n=20n = 20. Almost all cube volume is far from the center, toward corners: a uniform cube point satisfies E∥x∥2=n/3\E\norm{\vb{x}}^2 = n/3, so is typically distance ≈n/3\approx\sqrt{n/3} away, while the ball reaches only 11. Hit-or-miss sampling (throw points in the cube and count those in the ball) therefore stops working.
  • The grid does not scale. Quadrature with kk points per axis needs knk^n evaluations. With k=10k = 10 and n=100n = 100 this is 1010010^{100}: at 10910^9 evaluations per second, 109110^{91} seconds. This is the curse of dimensionality in quadrature and motivation for Monte Carlo, whose error decreases like O(N−1/2)\bigO(N^{-1/2}) regardless of nn (the constant, integrand standard deviation, can depend on dimension).

Leibniz’s rule: differentiation under the integral sign

Many functions are defined as integrals with a parameter, F(t)=∫abf(x,t) ⁣dxF(t) = \int_a^b f(x, t) \dd x: an expectation depending on model parameters, a Fourier transform, a partition function. To obtain its derivative, differentiating inside the integral is tempting. Leibniz’s rule says when this is legitimate and is proved with Fubini and the fundamental theorem of calculus.

Proof

Let G(t)=∫ab∂tf(x,t) ⁣dxG(t) = \int_a^b \partial_t f(x, t)\dd x, continuous by uniform continuity of ∂tf\partial_t f on the compact set. By Fubini (function ∂sf(x,s)\partial_s f(x, s) is continuous on the rectangle), then the fundamental theorem of calculus in variable ss,

∫ctG(s) ⁣ds=∫ab(∫ct∂sf(x,s) ⁣ds) ⁣dx=∫ab(f(x,t)−f(x,c)) ⁣dx=F(t)−F(c).\int_c^t G(s)\dd s = \int_a^b\Big(\int_c^t \partial_s f(x, s)\dd s\Big)\dd x = \int_a^b\big(f(x, t) - f(x, c)\big)\dd x = F(t) - F(c).

Since GG is continuous, the fundamental theorem says the left side is differentiable at tt with derivative G(t)G(t). Hence F′=GF' = G. For variable bounds, F(t)=H(α(t),β(t),t)F(t) = H(\alpha(t), \beta(t), t) with H(u,v,t)=∫uvf(x,t) ⁣dxH(u, v, t) = \int_u^v f(x, t)\dd x; partial derivatives of HH are −f(u,t)-f(u, t) (with respect to uu), f(v,t)f(v, t) (with respect to vv) and ∫uv∂tf\int_u^v\partial_t f (with respect to tt, by part one), and the chain rule combines all three terms.

∎

For integrals on unbounded domains, continuity on a compact set is insufficient and must be replaced by a parameter-independent bound: if ∣∂tf(x,t)∣≤g(x)\abs{\partial_t f(x, t)} \le g(x) for every tt in an interval and gg is integrable, differentiation inside remains legitimate (the dominated convergence theorem from measure theory). Under that assumption the trick is almost a method.

The assumptions matter. Let f(x,t)=t e−txf(x, t) = t\,e^{-tx} on [0,∞)[0, \infty), with t≥0t \ge 0. For each t>0t > 0, F(t)=∫0∞t e−tx ⁣dx=1F(t) = \int_0^\infty t\,e^{-tx}\dd x = 1, but at t=0t = 0 the integrand is zero and F(0)=0F(0) = 0: FF is not even continuous at 00, much less differentiable. There is no integrable bound gg independent of tt because sup⁡tt e−tx=1/(ex)\sup_t t\,e^{-tx} = 1/(ex) (attained at t=1/xt = 1/x), and ∫∞ ⁣dx/x\int^\infty \dd x/x diverges. Mass “escapes to infinity” as t→0t \to 0.

A second use, recurring in reparameterization gradients: if X=gθ(ε)\vb{X} = g_\theta(\vb{\eps}) with ε\vb{\eps} of fixed distribution, then ∇θ E[ℓ(gθ(ε))]=E[∇θ ℓ(gθ(ε))]\nabla_\theta\,\E[\ell(g_\theta(\vb{\eps}))] = \E[\nabla_\theta\,\ell(g_\theta(\vb{\eps}))], and Leibniz’s rule is exactly what permits interchanging derivative and expectation (with ℓ\ell and gθg_\theta differentiable and an integrable derivative bound). This works because the distribution integrated against does not depend on θ\theta: that is what reparameterization achieves through a change of variables.

Transforming densities: Box–Muller and flows

Everything is now ready for the two most-used change-of-variables applications in probability and machine learning.

Box–Muller

How do you make a Gaussian with a uniform random-number generator? If U1,U2U_1, U_2 are independent uniform on (0,1)(0, 1), the Box and Muller (1958) map

f(u1,u2)=(−2ln⁡u1cos⁡(2πu2), −2ln⁡u1sin⁡(2πu2))f(u_1, u_2) = \Big(\sqrt{-2\ln u_1}\cos(2\pi u_2),\ \sqrt{-2\ln u_1}\sin(2\pi u_2)\Big)

produces a pair of independent standard Gaussians. The idea is polar: r=−2ln⁡u1r = \sqrt{-2\ln u_1} and θ=2πu2\theta = 2\pi u_2. The interactive above includes it as a transformation: its Jacobian is ∣det⁡Jf∣=2π/u1\abs{\det J_f} = 2\pi/u_1, and dividing uniform density (p=1p = 1 on the square) by it gives u1/(2π)=e−∥y∥2/2/(2π)u_1/(2\pi) = e^{-\norm{\vb{y}}^2/2}/(2\pi) because u1=e−∥y∥2/2u_1 = e^{-\norm{\vb{y}}^2/2}. The full derivation, including inverse and its Jacobian, is this lesson’s proof exercise.

Normalizing flows

A normalizing flow parameterizes a complex density as the pushforward of a simple density (say Gaussian) by a trainable diffeomorphism fθf_\theta. By change of variables, its log likelihood is exact, not a bound:

log⁡pθ(y)=log⁡pX(fθ−1(y))+log⁡∣det⁡Jfθ−1(y)∣,\log p_\theta(\vb{y}) = \log p_X\big(f_\theta\inv(\vb{y})\big) + \log\abs{\det J_{f_\theta\inv}(\vb{y})},

and it is trained by maximizing ∑ilog⁡pθ(yi)\sum_i\log p_\theta(\vb{y}_i) over the data (normalizing flows; Papamakarios et al., arXiv:1912.02762). Practical use requires two things: an easy inverse and a cheap determinant. A general determinant costs O(n3)\bigO(n^3), and with nn in the thousands (a small image already has 32×32×3=307232 \times 32 \times 3 = 3072 coordinates) that is prohibitive each training step. Real NVP’s solution (Dinh, Sohl-Dickstein and Bengio, arXiv:1605.08803) is the coupling layer: split coordinates into (xa,xb)(\vb{x}_a, \vb{x}_b) and

ya=xa,yb=xb⊙exp⁡(s(xa))+t(xa),\vb{y}_a = \vb{x}_a, \qquad \vb{y}_b = \vb{x}_b \odot \exp\big(s(\vb{x}_a)\big) + t(\vb{x}_a),

with ss and tt arbitrary neural networks (they need not be invertible). The Jacobian is block triangular, with I\mat{I} and diag⁡(es(xa))\diag(e^{s(\vb{x}_a)}) on the diagonal, so

log⁡∣det⁡Jf∣=∑isi(xa)\log\abs{\det J_f} = \sum_i s_i(\vb{x}_a)

costs a sum and the inverse is explicit: xb=(yb−t(ya))⊙exp⁡(−s(ya))\vb{x}_b = (\vb{y}_b - t(\vb{y}_a)) \odot \exp(-s(\vb{y}_a)). The interactive has a two-dimensional coupling layer, and the implementation lesson builds one from scratch. Composing layers multiplies Jacobians and adds log determinants. In continuous time the sum becomes an integral,  ⁣dlog⁡p/ ⁣dt=−tr⁡(∂f/∂z)\dd\log p/\dd t = -\operatorname{tr}(\partial f/\partial\vb{z}) (instantaneous change of variables, lesson 20).

Implementation from scratch

First, double integrals as iterated integrals with Gauss–Legendre quadrature, the rule matching Fubini’s structure: nodes and weights on each axis, and the double integral is product wx⊤F wy\vb{w}_x\T\mat{F}\,\vb{w}_y with Fij=f(xi,yj)F_{ij} = f(x_i, y_j). The function allows iteration order selection and checks what the theorem does (and does not) say.

[ ]Double integrals as iterated integralsBrowser
import numpy as np
from numpy.polynomial.legendre import leggauss

def nodos(a, b, n):
    t, w = leggauss(n)
    return 0.5 * (b - a) * t + 0.5 * (b + a), 0.5 * (b - a) * w

def integral_2d(f, ax, bx, ay, by, n=40, orden="yx"):
    """Integral doble por iteración: Gauss-Legendre de n nodos en cada eje."""
    x, wx = nodos(ax, bx, n)
    y, wy = nodos(ay, by, n)
    F = f(x[:, None], y[None, :])            # F[i, j] = f(x_i, y_j)
    if orden == "yx":
        return wx @ (F @ wy)                 # primero y (suma por filas), después x
    return (wx @ F) @ wy                     # primero x, después y

# la gaussiana del primer ejercicio: exp(-(x^2 + 2xy + 3y^2)), integral exacta π/√2
gauss = lambda x, y: np.exp(-(x**2 + 2 * x * y + 3 * y**2))
exacta = np.pi / np.sqrt(2)
for n in [8, 16, 32, 64]:
    v = integral_2d(gauss, -6, 6, -6, 6, n)
    print(f"n = {n:2d}   integral = {v:.12f}   error = {abs(v - exacta):.1e}")
dif = integral_2d(gauss, -6, 6, -6, 6, 64, "yx") - integral_2d(gauss, -6, 6, -6, 6, 64, "xy")
print("diferencia entre los dos órdenes con n = 64:", dif)

# la constante de normalización de N(0, Σ): (2π) sqrt(det Σ) en dimensión 2
Sigma = np.array([[2.0, 0.6], [0.6, 1.0]])
P = np.linalg.inv(Sigma)
sin_normalizar = lambda x, y: np.exp(-0.5 * (P[0, 0] * x**2 + 2 * P[0, 1] * x * y + P[1, 1] * y**2))
print("constante de normalización:", integral_2d(sin_normalizar, -12, 12, -12, 12, 80),
      "  (2π) sqrt(det Σ) =", 2 * np.pi * np.sqrt(np.linalg.det(Sigma)))

# el contraejemplo (x² - y²)/(x² + y²)² en [0, 1]²: las integrales interiores tienen primitiva exacta
f = lambda x, y: (x**2 - y**2) / (x**2 + y**2) ** 2
print("\nregla producto simétrica:", integral_2d(f, 0, 1, 0, 1, 64, "yx"), integral_2d(f, 0, 1, 0, 1, 64, "xy"))
x, wx = nodos(0, 1, 40)
F_x = 1 / (1 + x**2)            # ∫_0^1 f(x, y) dy, con la primitiva y / (x² + y²)
G_y = -1 / (1 + x**2)           # ∫_0^1 f(x, y) dx
print("dy dx:", wx @ F_x, "  dx dy:", wx @ G_y, "  π/4 =", np.pi / 4)

The Gaussian converges spectrally (error falls from 10010^0 to 10−1110^{-11} going from n=8n = 8 to n=64n = 64 nodes per axis; what remains is the tail cut off outside [−6,6]2[-6, 6]^2), and both orders agree up to roundoff, as Fubini says. For the counterexample the product rule returns 00 in both orders: nodes are symmetric and f(x,y)=−f(y,x)f(x, y) = -f(y, x), so the sum cancels by construction. It is a third result, neither π/4\pi/4 nor −π/4-\pi/4, and nothing in code warns. Only exact inner integrals reveal the two differing values.

Now Box–Muller from scratch. The cell generates samples, checks with Kolmogorov–Smirnov tests that coordinates are N(0,1)\Normal(0, 1) and ∥z∥2\norm{\vb{z}}^2 is χ22\chi^2_2 (corresponding to r2=−2ln⁡u1r^2 = -2\ln u_1, exponential with mean 2), and compares the 2D histogram with change-of-variables density, with and without the determinant.

[ ]Box-Muller and its density by change of variablesBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(1)
N = 200_000
u1 = 1.0 - rng.random(N)            # en (0, 1], evita log(0)
u2 = rng.random(N)
r = np.sqrt(-2.0 * np.log(u1))
z = np.column_stack([r * np.cos(2 * np.pi * u2), r * np.sin(2 * np.pi * u2)])

print("medias:", z.mean(axis=0).round(3), "  covarianza:", np.cov(z.T).round(3).tolist())
print("KS coordenada 1 contra N(0,1): estadístico %.4f, p = %.3f" % stats.kstest(z[:, 0], "norm"))
print("KS coordenada 2 contra N(0,1): estadístico %.4f, p = %.3f" % stats.kstest(z[:, 1], "norm"))
print("KS de |z|² contra chi2(2):     estadístico %.4f, p = %.3f" % stats.kstest((z**2).sum(axis=1), "chi2", args=(2,)))

def log_p_boxmuller(y, con_det=True):
    """log p_Y(y) = log p_U(f^{-1}(y)) + log|det J_{f^{-1}}(y)|, con f^{-1}(y) = (e^{-|y|²/2}, ángulo/2π)."""
    ro2 = (y**2).sum(axis=-1)
    log_pu = np.zeros_like(ro2)                      # uniforme en el cuadrado unidad: p = 1
    log_det_inv = -ro2 / 2 - np.log(2 * np.pi)       # |det J_{f^{-1}}| = e^{-|y|²/2} / (2π)
    return log_pu + (log_det_inv if con_det else 0.0)

L, nb = 4.0, 40
H, xe, ye = np.histogram2d(z[:, 0], z[:, 1], bins=nb, range=[[-L, L], [-L, L]], density=True)
xc = 0.5 * (xe[1:] + xe[:-1]); yc = 0.5 * (ye[1:] + ye[:-1])
Y = np.stack(np.meshgrid(xc, yc, indexing="ij"), axis=-1)
area = (2 * L / nb) ** 2
for nombre, flag in [("con |det J|", True), ("sin |det J|", False)]:
    Pr = np.exp(log_p_boxmuller(Y, flag))
    print(f"{nombre}: integral de la predicción = {Pr.sum() * area:6.3f}   ½ ‖histograma - predicción‖₁ = {0.5 * np.abs(H - Pr).sum() * area:.3f}")

The three KS tests do not reject the hypothesis (pp-values are high), and the prediction with determinant integrates to 11 and resembles the histogram except for sampling noise, while without it it integrates to window area (8×8=648 \times 8 = 64) and differs absurdly. This is what the interactive showed, now in numbers.

An affine coupling layer in R2\R^2, with analytic log determinant, inverse and checks never to skip when implementing a flow: invertibility, Jacobian against finite differences, and whether the pushed density integrates to 1 and yields the same expectations as samples.

[ ]A 2D affine coupling and its log determinantBrowser
import numpy as np
from numpy.polynomial.legendre import leggauss

class AcoplamientoAfin:
    """y1 = x1,  y2 = x2 * exp(s(x1)) + t(x1): invertible, con jacobiano triangular."""
    def __init__(self, a=0.8, b=1.2, c=0.9):
        self.a, self.b, self.c = a, b, c
    def s(self, x1): return self.a * np.tanh(self.b * x1)
    def t(self, x1): return self.c * (x1**2 - 1)
    def forward(self, x):
        x1, x2 = x[..., 0], x[..., 1]
        y = np.stack([x1, x2 * np.exp(self.s(x1)) + self.t(x1)], axis=-1)
        return y, self.s(x1)                          # log|det J_f| = s(x1)
    def inverse(self, y):
        y1, y2 = y[..., 0], y[..., 1]
        x = np.stack([y1, (y2 - self.t(y1)) * np.exp(-self.s(y1))], axis=-1)
        return x, -self.s(y1)                         # log|det J_{f^-1}| = -s(y1)

def log_normal_2d(x):
    return -0.5 * (x**2).sum(axis=-1) - np.log(2 * np.pi)

capa = AcoplamientoAfin()
rng = np.random.default_rng(0)
x = rng.normal(size=(5, 2))
y, ld = capa.forward(x)
x_rec, ld_inv = capa.inverse(y)
print("error de invertibilidad:", np.abs(x - x_rec).max(), "  |log det f + log det f^-1|:", np.abs(ld + ld_inv).max())

def jac_num(f, x, h=1e-6):
    J = np.zeros((2, 2))
    for j in range(2):
        e = np.zeros(2); e[j] = h
        J[:, j] = (f(x + e) - f(x - e)) / (2 * h)
    return J
x0 = np.array([0.7, -0.4])
J = jac_num(lambda v: capa.forward(v)[0], x0)
print("log|det J| por diferencias finitas:", np.log(abs(np.linalg.det(J))), "  analítico:", capa.forward(x0)[1])

def log_p_y(y):
    x, ld_inv = capa.inverse(y)
    return log_normal_2d(x) + ld_inv

def rejilla(a, b, n):
    t, w = leggauss(n)
    return 0.5 * (b - a) * t + 0.5 * (b + a), 0.5 * (b - a) * w
n = 400
y1, w1 = rejilla(-7, 7, n); y2, w2 = rejilla(-9, 22, n)
Yg = np.stack(np.meshgrid(y1, y2, indexing="ij"), axis=-1)
Pg = np.exp(log_p_y(Yg))
W = w1[:, None] * w2[None, :]
print("\n∫ p_Y por la regla producto:", (Pg * W).sum())
Yb, _ = capa.forward(rng.normal(size=(400_000, 2)))
print("E[y2²] con la densidad:", (Yg[..., 1]**2 * Pg * W).sum(), "  con muestras transportadas:", (Yb[:, 1]**2).mean())

Density pYp_Y integrates to 11 to 10−610^{-6} and its second moment agrees with transported samples within Monte Carlo error (relative thousandths). log⁡∣det⁡J∣\log\abs{\det J} is the one place a flow can be wrong without anything failing: samples look the same and training runs, but the optimized likelihood is different.

Finally, ball volume and concentration by formula and simulation. Uniform points in the ball are generated with another change of variables: a uniform direction (a normalized Gaussian) and radius with density n rn−1n\,r^{n-1}, simulated by inverse distribution function r=U1/nr = U^{1/n}.

[ ]The ball that empties, with simulationBrowser
import numpy as np
from math import lgamma, pi, log, exp

def volumen_bola(n):
    return exp(0.5 * n * log(pi) - lgamma(0.5 * n + 1))

print("  n         V_n      V_n / 2^n    fracción en la cáscara del 5 %")
for n in [2, 3, 5, 10, 20, 50, 100]:
    print(f"{n:3d}  {volumen_bola(n):11.4e}  {volumen_bola(n) / 2**n:11.3e}   {1 - 0.95**n:.4f}")
print("máximo en n =", max(range(1, 30), key=volumen_bola), "   V_10/V_8 =", volumen_bola(10) / volumen_bola(8), "  2π/10 =", 2 * pi / 10)

rng = np.random.default_rng(3)
N = 200_000
print("\nMonte Carlo de acierto o fallo en el cubo [-1, 1]^n")
for n in [2, 5, 10, 15, 20]:
    X = rng.uniform(-1, 1, size=(N, n))
    aciertos = ((X**2).sum(axis=1) <= 1).sum()
    print(f"n = {n:2d}: aciertos {aciertos:6d} de {N}   V_n ≈ {aciertos / N * 2**n:.4f}   exacto {volumen_bola(n):.4f}")

n = 100
G = rng.normal(size=(20_000, n))
U = rng.random(20_000)
P = G / np.linalg.norm(G, axis=1, keepdims=True) * (U ** (1 / n))[:, None]
r = np.linalg.norm(P, axis=1)
print("\npuntos uniformes en la bola de R^100")
print("fracción con r > 0.95:", (r > 0.95).mean(), "  teórica:", 1 - 0.95**n)
print("radio mediano:", np.median(r), "  teórico 2^(-1/n):", 2 ** (-1 / n))

Simulation confirms the formula as far as it reaches: with n=10n = 10 only one in 400 samples falls inside the ball, with n=15n = 15 almost none, and with n=20n = 20 none in two hundred thousand, although V20≠0V_{20} \neq 0. This is hit-or-miss’s limit and why numerical methods introduces importance sampling. In the R100\R^{100} ball, simulated fraction in the 5 %5\,\% shell and median radius agree with 1−0.951001 - 0.95^{100} and 2−1/1002^{-1/100}.

With libraries: SciPy

scipy.integrate.dblquad and nquad perform adaptive quadrature (QUADPACK) and accept infinite bounds and bounds depending on outer variables. dblquad’s convention is treacherous: it integrates func(y, x) with x∈[a,b]x \in [a, b] outside and y∈[g(x),h(x)]y \in [g(x), h(x)] inside. And scipy.stats.multivariate_normal lets us compare the normalization constant with the one just proved.

[ ]dblquad, nquad and scipy.statsBrowser
import warnings
import numpy as np
from scipy import integrate, special, stats
from numpy.polynomial.legendre import leggauss

# 1. la gaussiana del primer ejercicio sobre todo R^2
val, err = integrate.dblquad(lambda y, x: np.exp(-(x*x + 2*x*y + 3*y*y)), -np.inf, np.inf, -np.inf, np.inf)
print(f"dblquad gaussiana: {val:.10f} ± {err:.1e}   π/√2 = {np.pi/np.sqrt(2):.10f}")

# 2. el contraejemplo, en los dos órdenes: aquí sí aparecen π/4 y -π/4
f = lambda x, y: (x*x - y*y) / (x*x + y*y)**2
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    a, _ = integrate.dblquad(lambda y, x: f(x, y), 0, 1, 0, 1)    # y es la variable interior
    b, _ = integrate.dblquad(lambda x, y: f(x, y), 0, 1, 0, 1)    # x es la variable interior
print(f"dy dx: {a:+.6f}   dx dy: {b:+.6f}   ±π/4 = {np.pi/4:.6f}")

# 3. la bola de R^3 con límites variables
def limites_y(x): return [-np.sqrt(1 - x*x), np.sqrt(1 - x*x)]
def limites_z(y, x):
    h = np.sqrt(max(0.0, 1 - x*x - y*y))
    return [-h, h]
v3, _ = integrate.nquad(lambda z, y, x: 1.0, [limites_z, limites_y, [-1, 1]])
print(f"volumen de la bola de R^3 con nquad: {v3:.8f}   4π/3 = {4*np.pi/3:.8f}")

# 4. la normalización de scipy.stats.multivariate_normal, con la regla producto de Gauss-Legendre
Sigma = np.array([[2.0, 0.6], [0.6, 1.0]]); mu = np.array([1.0, -1.0])
dist = stats.multivariate_normal(mu, Sigma)
t, w = leggauss(120)
gx, wg = 13 * t + 1.0, 13 * w; gy, wy = 13 * t - 1.0, 13 * w
Z = np.stack(np.meshgrid(gx, gy, indexing="ij"), axis=-1)
print("masa de la densidad de scipy:", (dist.pdf(Z) * wg[:, None] * wy[None, :]).sum())
print("pdf en la media:", dist.pdf(mu), "  1/((2π) sqrt(det Σ)) =", 1 / (2 * np.pi * np.sqrt(np.linalg.det(Sigma))))

# 5. el volumen de la bola con scipy.special: gamma y su logaritmo, que no se desborda
with np.errstate(all="ignore"):
    for n in [2, 10, 100, 400, 1000]:
        directo = np.pi**(n/2) / special.gamma(n/2 + 1)
        log10V = (0.5 * n * np.log(np.pi) - special.gammaln(n/2 + 1)) / np.log(10)
        print(f"n = {n:4d}   fórmula directa: {directo:.4e}   log10(V_n) con gammaln: {log10V:9.2f}")

dblquad returns π/4\pi/4 and −π/4-\pi/4 for the counterexample’s two orders, as proved by hand, and nquad handles variable-bound domains without changing coordinates. In the last part, special.gamma overflows for nn of order 340340 (returning inf and making the direct formula zero) although VnV_n is positive, and gammaln avoids overflow: the same pattern as logsumexp and log likelihoods. For n=1000n = 1000 not even VnV_n fits in a float64, so only its logarithm can be kept. Finally, measure actual grid-quadrature cost as dimension rises and numerically verify Leibniz’s rule and reparameterization.

[ ]The grid explodes; Leibniz and reparameterizationBrowser
import warnings
import numpy as np
from numpy.polynomial.legendre import leggauss
from scipy import integrate

warnings.simplefilter("ignore")

def gauss_producto(d, k, L=6.0):
    """∫ exp(-|x|²/2) sobre [-L, L]^d con la regla producto de k nodos por eje: k^d evaluaciones."""
    t, w = leggauss(k)
    t, w = L * t, L * w
    puntos = np.stack(np.meshgrid(*([t] * d), indexing="ij"), axis=-1).reshape(-1, d)
    pesos = np.prod(np.stack(np.meshgrid(*([w] * d), indexing="ij"), axis=-1).reshape(-1, d), axis=1)
    return (pesos * np.exp(-0.5 * (puntos**2).sum(axis=1))).sum()

print(" d   evaluaciones    error relativo")
for d in range(1, 6):
    v, exacto = gauss_producto(d, 10), (2 * np.pi) ** (d / 2)
    print(f"{d:2d}   {10**d:>10,d}    {abs(v - exacto) / exacto:.1e}")
for d in [10, 20, 50, 100]:
    print(f"d = {d:3d}: 10^{d} evaluaciones; a 10^9 por segundo, {10.0**(d - 9):.1e} s")

# Leibniz: F(t) = ∫_0^1 (x^t - 1)/ln x dx = ln(1 + t), con F'(t) = 1/(1 + t)
def F(t):
    g = lambda x: 0.0 if x == 0.0 or x == 1.0 else (x**t - 1) / np.log(x)
    return integrate.quad(g, 0, 1, points=[0.5])[0]
print()
for t in [0.5, 1.0, 3.0]:
    h = 1e-5
    print(f"t = {t}: F = {F(t):.8f}  ln(1+t) = {np.log(1 + t):.8f}   F' = {(F(t + h) - F(t - h)) / (2 * h):.7f}   1/(1+t) = {1 / (1 + t):.7f}")

# cuando falla: f(x, t) = t e^{-t x} en [0, ∞)
print()
for t in [1.0, 0.1, 0.01]:
    print(f"t = {t:5}:  ∫ t e^(-tx) dx = {integrate.quad(lambda x: t * np.exp(-t * x), 0, np.inf)[0]:.6f}")
print("en t = 0 el integrando es 0 y la integral vale 0: F salta de 1 a 0 y no se puede derivar.")

# reparametrización: ∇_σ E[(μ + σ ε)²] = E[∇_σ (μ + σ ε)²] = 2σ
rng = np.random.default_rng(0)
mu, sigma, N = 0.7, 1.3, 400_000
eps = rng.normal(size=N)
x = mu + sigma * eps
est_rep = 2 * x * eps
est_score = x**2 * ((x - mu)**2 / sigma**3 - 1 / sigma)
print(f"\nderivada exacta 2σ = {2 * sigma}")
print(f"reparametrización: {est_rep.mean():.4f} ± {est_rep.std() / np.sqrt(N):.4f}")
print(f"función score:     {est_score.mean():.4f} ± {est_score.std() / np.sqrt(N):.4f}")

Leibniz’s rule holds when numerically differentiating FF, and example t e−txt\,e^{-tx} shows the limit: for every t>0t > 0 the integral is 11 and at t=0t = 0 it is 00. The last block is the practical reason for the section: both estimators of ∂σ E[(μ+σε)2]\partial_\sigma\,\E[(\mu + \sigma\eps)^2] are unbiased, but reparameterization’s typical error is about three times smaller with the same samples. The cost table tells the grid story: error grows with dd even with ten nodes per axis, and times move from seconds in d=10d = 10 to 109110^{91} seconds in d=100d = 100.

Common mistakes

Exercises

NumericA Gaussian with a cross term
Calculate ∬R2exp⁡ ⁣(−(x2+2xy+3y2)) ⁣dx ⁣dy\displaystyle\iint_{\R^2}\exp\!\big(-(x^2 + 2xy + 3y^2)\big)\dd x\dd y.
NumericBall volume in R^10
What is the unit-ball volume of R10\R^{10}?
NumericChanging integration order
Calculate ∫01 ⁣ ⁣∫x1e−y2 ⁣dy ⁣dx\displaystyle\int_0^1\!\!\int_x^1 e^{-y^2}\dd y\dd x.
QuizWhat fails in the counterexample
Let 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, with ∫01 ⁣∫01f ⁣dy ⁣dx=π/4\int_0^1\!\int_0^1 f\dd y\dd x = \pi/4 and ∫01 ⁣∫01f ⁣dx ⁣dy=−π/4\int_0^1\!\int_0^1 f\dd x\dd y = -\pi/4. Which statements are true?

More than one answer may be correct.

NumericDensity of a sum and difference
Let X,YX, Y be independent uniform on (0,1)(0, 1) and (U,V)=(X+Y, X−Y)(U, V) = (X + Y,\ X - Y). What is joint density pU,V(1,0.2)p_{U,V}(1, 0.2)?
NumericWhen the shell contains almost everything
What is the smallest dimension nn for which the thickness-ε=0.01\varepsilon = 0.01 shell of the unit ball of Rn\R^n contains at least 99 %99\,\% of its volume?
ProofBox-Muller
Prove: Let U1,U2U_1, U_2 be independent uniform variables on (0,1)(0, 1). Then Z=f(U1,U2)=(−2ln⁡U1cos⁡2πU2, −2ln⁡U1sin⁡2πU2)\vb{Z} = f(U_1, U_2) = \big(\sqrt{-2\ln U_1}\cos 2\pi U_2,\ \sqrt{-2\ln U_1}\sin 2\pi U_2\big) has density φ(z)=12πe−∥z∥2/2\varphi(\vb{z}) = \dfrac{1}{2\pi}e^{-\norm{\vb{z}}^2/2} on R2\R^2.
0
ff is a bijection from the open square (0,1)2(0, 1)^2 onto R2\R^2 minus a half-line (a set of measure zero), and the density of (U1,U2)(U_1, U_2) is 11 on the square.

Step 1 of 4. Which formula do you use?

ProofDifferentiating under the integral sign
Prove: For I(t)=∫0∞e−x2cos⁡(tx) ⁣dxI(t) = \displaystyle\int_0^\infty e^{-x^2}\cos(tx)\dd x, show that I′(t)=−t2 I(t)I'(t) = -\dfrac t2\,I(t) and deduce I(t)=π2 e−t2/4I(t) = \dfrac{\sqrt\pi}{2}\,e^{-t^2/4}.
0
Use ∫0∞e−x2 ⁣dx=π/2\int_0^\infty e^{-x^2}\dd x = \sqrt\pi/2 (Gaussian integral).

Step 1 of 4. What hypothesis justifies exchanging the derivative in tt with the integral in [0,∞)[0, \infty)?

CodeThe log density of a transformed variable
Implement log_density_pushforward(log_p_base, f_inv, jac_f_inv, y) to return log⁡pY(y)\log p_Y(\vb{y}) for a batch y of shape (N, d), with log⁡pY(y)=log⁡pX(f−1(y))+log⁡∣det⁡Jf−1(y)∣\log p_Y(\vb{y}) = \log p_X(f^{-1}(\vb{y})) + \log\abs{\det J_{f^{-1}}(\vb{y})}. log_p_base(x) receives (N, d) and returns (N,); f_inv(y) returns (N, d); jac_f_inv(y) returns the inverse Jacobian at each point, with shape (N, d, d). Use np.linalg.slogdet to avoid determinant overflow.
import numpy as np

def log_density_pushforward(log_p_base, f_inv, jac_f_inv, y):
  """log p_Y(y) = log p_X(f^{-1}(y)) + log |det J_{f^{-1}}(y)|, para y de forma (N, d)."""
  # tu código
  return np.zeros(len(y))
Shift+Enter to run

Summary

Key idea
A multiple integral is calculated by slicing (Fubini, if the integral converges absolutely) and simplified by adapting coordinates to the geometry: the factor ∣det⁡J∣\abs{\det J} measures how much volumes stretch, and therefore also determines how probability densities transform.
  • A multiple integral is the limit of Riemann sums over rectangles; continuous functions are integrable, and in general it suffices that discontinuities form a set of measure zero.
  • Fubini: for ff continuous on a rectangle, or absolutely integrable, iterated integrals equal the double integral in either order (Tonelli, if f≥0f \ge 0). Without absolute integrability the order matters: (x2−y2)/(x2+y2)2(x^2 - y^2)/(x^2 + y^2)^2 on [0,1]2[0, 1]^2 gives π/4\pi/4 and −π/4-\pi/4. When changing order, the bounds must be recalculated.
  • Change of variables: ∫Vf=∫Uf∘φ ∣det⁡Jφ∣\int_V f = \int_U f\circ\varphi\,\abs{\det J_\varphi}. Hence densities: pY(y)=pX(f−1(y)) ∣det⁡Jf−1(y)∣p_Y(\vb{y}) = p_X(f\inv(\vb{y}))\,\abs{\det J_{f\inv}(\vb{y})}. Use the inverse Jacobian and absolute value.
  • Polar (rr), cylindrical (rr), and spherical (ρ2sin⁡φ\rho^2\sin\varphi) coordinates adapt integration to symmetry. For radial integrands in Rn\R^n, ∫h(∥x∥) ⁣dx=∫0∞h(r) nVn rn−1 ⁣dr\int h(\norm{\vb{x}})\dd\vb{x} = \int_0^\infty h(r)\,nV_n\,r^{n-1}\dd r.
  • The Gaussian integral, ∫e−x2=π\int e^{-x^2} = \sqrt\pi, follows by switching to polar coordinates, and the normalization constant of N(μ,Σ)\Normal(\vb{\mu}, \mat{\Sigma}) is (2π)n/2det⁡(Σ)1/2(2\pi)^{n/2}\det(\mat{\Sigma})^{1/2} (spectral theorem plus a linear change).
  • The unit ball has volume Vn=πn/2/Γ(n/2+1)V_n = \pi^{n/2}/\Gamma(n/2 + 1): maximal at n=5n = 5 and then tending to zero. A fraction 1−(1−ε)n1 - (1 - \eps)^n of the volume is in the shell of thickness ε\eps (99.4 %99.4\,\% for ε=5 %\eps = 5\,\% in n=100n = 100), while the grid costs knk^n evaluations.
  • Leibniz’s rule allows differentiation under the integral when ff and ∂tf\partial_t f are continuous on a compact set or ∂tf\partial_t f has an integrable bound independent of the parameter. This underlies reparameterization and Feynman’s trick.
  • In normalizing flows, log⁡pY=log⁡pX∘f−1+log⁡∣det⁡Jf−1∣\log p_Y = \log p_X\circ f\inv + \log\abs{\det J_{f\inv}}, and coupling layers make that determinant cheap using triangular Jacobians.