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 . To make it a density, divide by its integral over , and that constant, , is not a matter of taste: it appears in every likelihood, KL between Gaussians and Bayesian update.
- Calculate expectations. . An expectation is an integral with respect to a density, and when has 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 , what density does 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 .
There are also two unexpected gifts from an integration lesson. One is geometric: the unit-ball volume of tends to zero as 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 -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 be a closed rectangle of volume . Partition each edge into subintervals; products of one subinterval from each edge are rectangles covering and touching only at boundaries. This is a partition . For a bounded function define, as in lesson 2, lower and upper Darboux sums:
With and , is the volume of the solid between and the graph of . With we obtain volume (or area) of . With density instead of , we obtain probability of .
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
is compact, so is uniformly continuous: given there exists such that whenever . Take a partition whose rectangles all have diameter less than . On each (compact), attains maximum and minimum, whose difference is less than . Hence and
Since 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 by zero makes the integrand jump on boundary . Lebesgue’s criterion covers everything. A set has measure zero if for each it can be covered by countably many rectangles of total volume less than . Finite or countable sets, segments and graphs of continuous functions in have measure zero.
(The proof is in Hubbard and Hubbard, chapter 4.) An immediate consequence: if is continuous and bounded on bounded set whose boundary has measure zero (a ball, polygon, region between continuous graphs), then is discontinuous only on and exists. These are our working domains. A function like 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 , monotonicity ( implies ), , and domain additivity, 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 cuts the solid and its cross-sectional area is measured; volume is the sum (integral) of those areas along . This is an iterated integral, . The natural question is whether the result depends on slicing direction and agrees with the double integral.
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 follows from uniform continuity: if then for every , hence . Equality remains. Take partitions and , with and the minimum and maximum of on . For and each , for every ; integrate in and sum in ,
The bound holds for every in the interval, so also bounds infimum and supremum of there. Multiply by and sum in to get . Since is integrable, and approach as is refined, and the chain forces . The other order is identical.
∎For nonrectangular domains, an elementary region lies between two graphs, with continuous, and then . Changing order requires rewriting bounds describing the same region as , .
Tonelli, Fubini and the counterexample
The preceding theorem suffices for continuous functions on compact sets. Probability requires integration over all 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 (always possible) and check the result is finite; then Fubini to . 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, with , is continuous and Fubini applies; by antisymmetry the integral is exactly . And symmetric quadrature on also gives (seen below): neither nor , but a third number without meaning. Interchanging order without checking absolute integrability is an unproved assertion.
Change of variables
In one variable substitution gives . In several variables the Jacobian determinant takes the role of , and an absolute value appears that in one variable is hidden in bound orientation.
The geometry is from lesson 7. A differentiable map , magnified near point , is its linearization . A linear matrix turns any cube into a parallelepiped of times the volume (determinant as volume factor). Thus a tiny cell of volume occupies volume , and summing on image cells equals summing times each cell’s scale factor.
Proof
Sketch, with the two conceptual steps. (1) Linear case. For , the image of rectangle is a parallelepiped of volume , the determinant as volume (linear algebra lesson 6); with step function the formula sums that equality. (2) Local case. Let be a cube of side and center , with . By uniform differentiability on a compact set, with for small . Then and : the image of lies inside the image under of a slightly larger cube, with volume at most , with as . Sum over cells of a compact-set partition and take limits to obtain . Applying the same to gives the reverse inequality, yielding equality for , then for step functions and, by approximation, integrable .
∎Absolute value is essential because a volume integral cannot be negative: if reverses orientation (like ) its determinant is negative, while the image region still has positive volume.
From the formula to densities
Now take a random variable with density , and transformation with a diffeomorphism. For any set ,
where the last step substitutes using the change of variables above (with ). Since this holds for every , the integrand is the density of .
Both forms are the same because (chain rule applied to ) and . In logarithms, as used in practice,
The next interactive shows both sides at once: cells stretching or compressing according to , and a sample histogram confirming the formula.
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 changes volume units. Second, using forward Jacobian instead of the inverse multiplies what should be ; harmless only when the determinant equals . 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 : , with and . The Jacobian matrix and determinant are
Cylindrical in : polar plus height , with .
Spherical in , with , colatitude (angle with axis ) and : , , . The three columns of are
They are pairwise orthogonal (check dot products) and their lengths are , and . For a matrix of orthogonal columns, is diagonal with squared lengths, and is their product:
Geometrically, a spherical cell is nearly a box with sides , and , explaining each factor. With , and no absolute value is needed. The origin (polar), axis (cylindrical) and axis , where (spherical), are measure-zero sets where the map ceases to be injective or its Jacobian vanishes, as is half-plane or ray where angle endpoints meet; the formula still holds.
In dimension there is no need to construct general spherical coordinates. For radial integrands, , scaling suffices: ball has volume because multiplies volumes by . The shell between radii and has volume , and a Riemann–Stieltjes sum with respect to gives the result.
(This is a Riemann–Stieltjes integral, from lesson 2, with respect to , whose derivative is .) With polar factor reappears, and with , .
The Gaussian integral
Function has no elementary antiderivative, yet its integral over the entire line, an improper integral, equals exactly . 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 . By Fubini (the integrand is continuous on a rectangle), . Disk of radius lies inside the square, and the square inside disk . Since the integrand is positive,
In polar coordinates, , because does have an antiderivative, . Therefore
and as both bounds tend to : .
∎Factor in turns an integral with no antiderivative into one with one: without the Jacobian, would still be impossible. The figure makes this visible. Rings of thickness have area , and unrolling them shows why: the strip at radius is long.
From the one-dimensional integral, scaling and translation give normalization constants for all scalar Gaussians: . And from Gamma: with , , 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 diagonalizes in an orthonormal basis by the spectral theorem, with orthogonal and , . And a linear substitution has its matrix as Jacobian.
Proof
Translation has Jacobian 1. Set , with Jacobian and , because is orthogonal and . The exponent becomes . The integral becomes , and by Tonelli (the integrand is positive) that integral is the product of one-dimensional integrals . The second form follows from , with .
∎Thus the density of is , 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 (a negative eigenvalue makes the exponent grow without bound in its direction and the integral diverge; with a zero eigenvalue has no inverse), and the spectral theorem gives the rotation decoupling variables.
Ball volume in
The Gaussian integral just calculated in can also be calculated in in two ways. Factoring gives . With radial integration,
where recognizes and was used. Equating both expressions yields unit-ball volume:
With we recover , and . Relation also gives recurrence , and with it nearly the whole story: exceeds only while , that is, for . Thus the odd subsequence grows to and the even one to , then both decrease; since , the maximum of the whole sequence is at .
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 10 | 20 | |
|---|---|---|---|---|---|---|---|---|---|---|
| 2 | 3.1416 | 4.1888 | 4.9348 | 5.2638 | 5.1677 | 4.7248 | 4.0587 | 2.5502 | 0.0258 |
The maximum is at (), after which volume decreases faster than any exponential: , as follows from Stirling’s formula. In dimension the unit ball has volume .
Concentration in the shell
The ball of radius has volume , so the fraction of unit-ball volume within distance of the center is . The fraction in shell is its complement:
With and it is : of the ball’s volume lies in the outer of its radius. Radial density of a uniform point is on , with median (in , ): 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 of volume , and fraction is in , in and in . Almost all cube volume is far from the center, toward corners: a uniform cube point satisfies , so is typically distance away, while the ball reaches only . 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 points per axis needs evaluations. With and this is : at evaluations per second, seconds. This is the curse of dimensionality in quadrature and motivation for Monte Carlo, whose error decreases like regardless of (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, : 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 , continuous by uniform continuity of on the compact set. By Fubini (function is continuous on the rectangle), then the fundamental theorem of calculus in variable ,
Since is continuous, the fundamental theorem says the left side is differentiable at with derivative . Hence . For variable bounds, with ; partial derivatives of are (with respect to ), (with respect to ) and (with respect to , 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 for every in an interval and 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 on , with . For each , , but at the integrand is zero and : is not even continuous at , much less differentiable. There is no integrable bound independent of because (attained at ), and diverges. Mass “escapes to infinity” as .
A second use, recurring in reparameterization gradients: if with of fixed distribution, then , and Leibniz’s rule is exactly what permits interchanging derivative and expectation (with and differentiable and an integrable derivative bound). This works because the distribution integrated against does not depend on : 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 are independent uniform on , the Box and Muller (1958) map
produces a pair of independent standard Gaussians. The idea is polar: and . The interactive above includes it as a transformation: its Jacobian is , and dividing uniform density ( on the square) by it gives because . 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 . By change of variables, its log likelihood is exact, not a bound:
and it is trained by maximizing 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 , and with in the thousands (a small image already has 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 and
with and arbitrary neural networks (they need not be invertible). The Jacobian is block triangular, with and on the diagonal, so
costs a sum and the inverse is explicit: . 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, (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 with . The function allows iteration order selection and checks what the theorem does (and does not) say.
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 to going from to nodes per axis; what remains is the tail cut off outside ), and both orders agree up to roundoff, as Fubini says. For the counterexample the product rule returns in both orders: nodes are symmetric and , so the sum cancels by construction. It is a third result, neither nor , 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 and is (corresponding to , exponential with mean 2), and compares the 2D histogram with change-of-variables density, with and without the determinant.
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 (-values are high), and the prediction with determinant integrates to and resembles the histogram except for sampling noise, while without it it integrates to window area () and differs absurdly. This is what the interactive showed, now in numbers.
An affine coupling layer in , 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.
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 integrates to to and its second moment agrees with transported samples within Monte Carlo error (relative thousandths). 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 , simulated by inverse distribution function .
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 only one in 400 samples falls inside the ball, with almost none, and with none in two hundred thousand, although . This is hit-or-miss’s limit and why numerical methods introduces importance sampling. In the ball, simulated fraction in the shell and median radius agree with and .
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 outside and inside. And scipy.stats.multivariate_normal lets us compare the normalization constant with the one just proved.
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 and 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 of order (returning inf and making the direct formula zero) although is positive, and gammaln avoids overflow: the same pattern as logsumexp and log likelihoods. For not even 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.
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 , and example shows the limit: for every the integral is and at it is . The last block is the practical reason for the section: both estimators of 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 even with ten nodes per axis, and times move from seconds in to seconds in .
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Which formula do you use?
Step 1 of 4. What hypothesis justifies exchanging the derivative in with the integral in ?
log_density_pushforward(log_p_base, f_inv, jac_f_inv, y) to return for a batch y of shape (N, d), with . 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))Summary
- 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 continuous on a rectangle, or absolutely integrable, iterated integrals equal the double integral in either order (Tonelli, if ). Without absolute integrability the order matters: on gives and . When changing order, the bounds must be recalculated.
- Change of variables: . Hence densities: . Use the inverse Jacobian and absolute value.
- Polar (), cylindrical (), and spherical () coordinates adapt integration to symmetry. For radial integrands in , .
- The Gaussian integral, , follows by switching to polar coordinates, and the normalization constant of is (spectral theorem plus a linear change).
- The unit ball has volume : maximal at and then tending to zero. A fraction of the volume is in the shell of thickness ( for in ), while the grid costs evaluations.
- Leibniz’s rule allows differentiation under the integral when and are continuous on a compact set or has an integrable bound independent of the parameter. This underlies reparameterization and Feynman’s trick.
- In normalizing flows, , and coupling layers make that determinant cheap using triangular Jacobians.