Module contents
Lesson 10 of 24Core 95 min

Transformations of random variables and change of variables

How a density changes when its variable is transformed: the Jacobian as a volume-change factor, sums of log-determinants in transformation chains (the exact basis of normalizing flows), convolution for sums of independent variables, Box–Muller and order statistics.

After this lesson you can

  • Derive the density of Y = g(X) in one and several dimensions, including non-injective transformations.
  • Calculate log-densities of composed transformations by summing each layer’s log|det J|.
  • Obtain the law of sums of independent variables by convolution.
  • Derive the Box–Muller transform and gamma–beta relationships by change of variables.
  • Calculate the laws of the minimum, maximum and k-th order statistic.

Before you start

Motivation: an exact-density model built from changes of variables

You want a generative model of data in Rd\R^d with two properties at once: you can sample from it and evaluate its density p(x)p(\vb{x}) exactly, without bounds or approximations, to train it by maximum likelihood. The normalizing-flow recipe is surprisingly short. Start with a variable of known law, Z∼N(0,I)\vb{Z} \sim \Normal(\vb{0}, \mat{I}), and apply an invertible, differentiable function X=fθ(Z)\vb{X} = f_\theta(\vb{Z}) parameterized by a neural network. Sampling means evaluating fθf_\theta. Evaluating the density uses this lesson’s formula: the density of X\vb{X} at x\vb{x} is that of Z\vb{Z} at fθ−1(x)f_\theta\inv(\vb{x}), corrected for how much fθf_\theta stretches volume around that point.

That correction, the Jacobian, appears everywhere a random variable is transformed:

  • Reparameterization. A variational autoencoder writes z=μ+σ⊙ε\vb{z} = \vb{\mu} + \vb{\sigma} \odot \vb{\varepsilon} with ε∼N(0,I)\vb{\varepsilon} \sim \Normal(\vb{0}, \mat{I}) and needs to know the resulting law.
  • Sampling. Your library’s random-number generator only knows how to produce uniform variables. Everything else (normal, exponential, categorical) comes from transforming them.
  • Sums and accumulation. A system’s total error is a sum of independent errors. What density does that sum have?
  • Ordering. The maximum of nn scores, the sample median, the kk largest in a batch: laws of order statistics.

This lesson answers four connected questions.

  1. One dimension. If Y=g(X)Y = g(X), what is the density of YY? We must count how much gg stretches and what to do when gg folds the line onto itself.
  2. Several dimensions. What role does the Jacobian determinant play, and why do the log-determinants in a chain of layers add?
  3. Sums and coordinate changes. Convolution is a change of variables with Jacobian 1; polar coordinates give Box–Muller, followed by ratios, the beta law, Student’s tt and the Cauchy law.
  4. Order statistics. The laws of the minimum, maximum and kk-th statistic, and an identity between binomial tails and the beta distribution function proved without integration.

Everything that follows applies a single calculus theorem, change of variables in integrals (calculus lesson), to the pushforward law you already know.

One dimension: density dilutes where gg stretches

Let XX be a random variable with density pXp_X and let Y=g(X)Y = g(X). The law of YY is the pushforward measure PY(B)=P(X∈g−1(B))\Pr_Y(B) = \Pr(X \in g\inv(B)), and our task is to read off its density. Start with the clean case: gg is differentiable and monotone.

Proof

Let B⊆JB \subseteq J be Borel. Since P(X∈I)=1\Pr(X \in I) = 1,

P(Y∈B)=P(X∈g−1(B))=∫g−1(B)pX(x) ⁣dx=∫BpX(g−1(y)) ∣(g−1)′(y)∣ ⁣dy.\begin{aligned} \Pr(Y \in B) &= \Pr\big(X \in g\inv(B)\big) = \int_{g\inv(B)} p_X(x)\dd x \\ &= \int_{B} p_X\big(g\inv(y)\big)\,\abs{\big(g\inv\big)'(y)}\dd y. \end{aligned}

The last equality is the change of variables x=g−1(y)x = g\inv(y) in an integral, valid because g−1g\inv is C1C^1 and its derivative does not vanish; the absolute value accounts for the fact that, if gg is decreasing, the change reverses the limits of integration. A function whose integral over every Borel set gives the law of YY is, by uniqueness in the Radon–Nikodym theorem, a density of YY (unique up to sets of measure zero). ■\blacksquare

∎

Using distribution functions, the same result takes one line. If gg is increasing, FY(y)=P(g(X)≤y)=FX(g−1(y))F_Y(y) = \Pr(g(X) \le y) = F_X(g\inv(y)), and differentiating gives pY(y)=pX(g−1(y)) (g−1)′(y)p_Y(y) = p_X(g\inv(y))\,(g\inv)'(y). If it is decreasing, FY(y)=1−FX(g−1(y))F_Y(y) = 1 - F_X(g\inv(y)) and the derivative changes sign, so the absolute value appears automatically.

The interpretation matters more than the formula. A density is not a probability but a probability per unit length. The mass of a tiny interval [x,x+ ⁣dx][x, x + \dd x] is pX(x) ⁣dxp_X(x)\dd x, and gg sends it to an interval of length ∣g′(x)∣ ⁣dx\abs{g'(x)}\dd x with the same mass. If gg stretches by a factor of ∣g′(x)∣\abs{g'(x)}, the same mass spreads across more length and the density is divided by that factor:

pY(y) ∣ ⁣dy∣=pX(x) ∣ ⁣dx∣⟺pY(y)=pX(x)∣ ⁣dy/ ⁣dx∣.p_Y(y)\,\abs{\dd y} = p_X(x)\,\abs{\dd x} \qquad\Longleftrightarrow\qquad p_Y(y) = \frac{p_X(x)}{\abs{\dd y/\dd x}}.

The first figure shows this. Take eight bands of XX with exactly the same probability 1/81/8 (hence narrow where pXp_X is high and wide in the tails), transport them through gg, and measure each band’s width in yy.

InteractiveProbability dilutes where gg stretches
Center: y=g(x)y = g(x). Below, the density of XX in eight bands of equal area. Right, that of YY: height = mass 1/81/8 divided by band width
−2−20022y = g(x)xdensity of Xdensity of Y
  • eight bands of XX with mass 1/81/8 (one color each)
  • formula pX(g−1(y)) ∣(g−1)′(y)∣p_X(g^{-1}(y))\,\abs{(g^{-1})'(y)}
  • simulation
  • probe
Law of XX
Probe x∗x^*, y∗=g(x∗)y^* = g(x^*)0.60, −2.21
pX(x∗)p_X(x^*)0.333
∣g′(x∗)∣\abs{g'(x^*)} (stretch factor)0.878
pY(y∗)=pX(x∗)/∣g′(x∗)∣p_Y(y^*) = p_X(x^*) / \abs{g'(x^*)}0.380
Mass of each band1/8 = 0.125
Drag the five graph nodes to shape the function gg and move the magenta probe along its graph. Each color represents a band of XX with probability 1/81/8 (below, with equal areas) and its image in yy (right, where each bar's height is 1/81/8 divided by its width). Notice that where gg is steep the bars are low and wide, and where it is almost flat they are narrow and tall: this matches the continuous curve in the right panel, pX(x)/∣g′(x)∣p_X(x)/\abs{g'(x)}. Try ‘Flat center’, ‘Sigmoid’ and the uniform law, and turn on the simulation.

What you should have seen:

  • The bars on the right match the curve. Each bar is an average density (mass divided by width), and the continuous curve is the exact density; they agree ever more closely as the bands become thinner, and the simulated points fall on the curve.
  • Where gg is almost flat, the density of YY shoots up. With “Sigmoid” the tails of XX are compressed against the endpoints and the density of YY accumulates there (bars extending outside the panel have an ▶\blacktriangleright mark). With “Flat center” the entire central part of XX piles up around y=0y = 0.
  • If gg is decreasing, the density is the same as with the reflected function. The absolute value of g′g' distinguishes only how much it stretches, not its direction.
  • The probe reads the formula. pX(x∗)p_X(x^*) divided by ∣g′(x∗)∣\abs{g'(x^*)} gives pY(y∗)p_Y(y^*), the value read from the right panel at y∗y^*.

When gg is not injective: sum over the preimages

Many useful transformations fold the line: x2x^2, ∣x∣\abs{x}, sin⁡x\sin x. Then each value yy can come from several xx, and the probability of a neighborhood of yy is the sum of the masses arriving through all branches.

Proof

For Borel BB, P(Y∈B)=∑kP(X∈Ik,  gk(X)∈B)\Pr(Y \in B) = \sum_k \Pr(X \in I_k,\; g_k(X) \in B) by countable additivity. Each term is ∫gk−1(B)pX(x) ⁣dx=∫B∩JkpX(gk−1(y)) ∣(gk−1)′(y)∣ ⁣dy\int_{g_k\inv(B)} p_X(x)\dd x = \int_{B \cap J_k} p_X(g_k\inv(y))\,\abs{(g_k\inv)'(y)}\dd y by the previous theorem applied to the branch kk. Sum the integrals and exchange the sum and integral (everything is nonnegative, by Tonelli). ■\blacksquare

∎

Divergent densities are not peculiar to this example. They occur precisely at the critical values of gg, those yc=g(xc)y_c = g(x_c) with g′(xc)=0g'(x_c) = 0. Near a critical point with g′′(xc)≠0g''(x_c) \ne 0, g(x)≈yc+12g′′(xc)(x−xc)2g(x) \approx y_c + \tfrac12 g''(x_c)(x - x_c)^2: the two preimages are 2(y−yc)/g′′(xc)\sqrt{2(y - y_c)/g''(x_c)} away from xcx_c, and ∣g′∣\abs{g'} equals 2 g′′(xc) (y−yc)\sqrt{2\,g''(x_c)\,(y - y_c)} there. Each branch’s contribution grows like (y−yc)−1/2(y - y_c)^{-1/2}, an integrable singularity: the total mass is still one. The second figure stacks the branches so you can see where each piece of the density comes from.

InteractivePreimages and singularities at critical values
Center: y=g(x)y = g(x). Below, pXp_X. Right, pYp_Y stacked by branch (clipped at 1.5: the peaks are integrable singularities)
−4−2024036density of Xdensity of Y
  • preimage 1 (leftmost)
  • preimage 2
  • preimage 3
  • sum = pYp_Y
  • simulation
1.00
0.0
Level y∗y^*1.20
Preimages xkx_k−1.10, 1.10
pX(xk)/∣g′(xk)∣p_X(x_k)/\abs{g'(x_k)}0.100 + 0.100
pY(y∗)p_Y(y^*) = sum0.200
Choose gg and drag the magenta point on the right axis to raise or lower the level y∗y^*. At that height the preimages xkx_k appear (one color per preimage, numbered left to right) and, on the right, their contributions pX(xk)/∣g′(xk)∣p_X(x_k)/\abs{g'(x_k)} are stacked in a bar whose total length is pY(y∗)p_Y(y^*). With the cubic x3−3axx^3 - 3ax, raise aa above 00: a region with three preimages appears between two critical values, where the density shoots up. Move the mean of XX and see how mass is distributed between branches.

What you should have seen:

  • The density of YY is the sum of the branches. In Y=X2Y = X^2 with μ=0\mu = 0 the two contributions are equal; moving μ\mu makes the branch closer to the maximum of pXp_X dominate.
  • The peaks are at critical values. For sin⁡X\sin X they appear at y=±1y = \pm 1, for X2X^2 at y=0y = 0, and for the cubic at ±2a3/2\pm 2a^{3/2}. Between two critical values there are more preimages than outside them, and the density’s height jumps.
  • The simulation validates the sum, not its individual terms. The simulated points match the outline of the sum, but each color separately is not observable: seeing yy does not tell you which branch it came from.

Several dimensions: the Jacobian as a volume-change factor

In Rn\R^n the derivative of gg is a matrix. The Jacobian matrix (calculus lesson) of g=(g1,…,gn)g = (g_1, \dots, g_n) at x\vb{x} is Jg(x)=(∂gi∂xj(x))ij\mat{J}_g(\vb{x}) = \big(\pd{g_i}{x_j}(\vb{x})\big)_{ij}, the best linear approximation of gg near x\vb{x}. Its determinant has a geometric interpretation: the linear map J\mat{J} multiplies volumes by ∣det⁡J∣\abs{\det \mat{J}} (the determinant is the signed volume of the image of the unit cube). Thus gg takes a tiny cube with side ε\varepsilon and volume εn\varepsilon^n to a set of volume ≈∣det⁡Jg(x)∣ εn\approx \abs{\det\mat{J}_g(\vb{x})}\,\varepsilon^n with the same mass. The density is divided by that factor, just as in one dimension.

Proof

This is the one-dimensional proof using the change-of-variables theorem for multiple integrals. For Borel B⊆VB \subseteq V,

P(Y∈B)=∫g−1(B)pX(x) ⁣dx=∫BpX(g−1(y)) ∣det⁡Jg−1(y)∣ ⁣dy,\Pr(\vb{Y} \in B) = \int_{g\inv(B)} p_{\vb{X}}(\vb{x})\dd\vb{x} = \int_B p_{\vb{X}}\big(g\inv(\vb{y})\big)\,\abs{\det \mat{J}_{g\inv}(\vb{y})}\dd\vb{y},

and uniqueness of the density finishes the proof. The second form follows from the chain rule applied to g∘g−1=idg \circ g\inv = \mathrm{id}: Jg(x) Jg−1(y)=I\mat{J}_g(\vb{x})\,\mat{J}_{g\inv}(\vb{y}) = \mat{I}, hence det⁡Jg−1(y)=1/det⁡Jg(x)\det\mat{J}_{g\inv}(\vb{y}) = 1/\det\mat{J}_g(\vb{x}). ■\blacksquare

∎

The two forms serve different purposes. If you know the inverse in closed form, use Jg−1\mat{J}_{g\inv} and multiply. If you know gg and have x\vb{x} at hand, divide by ∣det⁡Jg(x)∣\abs{\det\mat{J}_g(\vb{x})}: there is no need to invert a matrix, only evaluate a determinant.

A practical consequence is the auxiliary-variable trick. If you only want the law of a function h(X)h(\vb{X}) taking values in fewer dimensions, there is no square Jacobian to use. Extend hh to a diffeomorphism by adding convenient auxiliary variables, apply the theorem, and integrate out the auxiliaries (Fubini–Tonelli). That is exactly what convolution, the ratio of normals and the gamma–beta relationship do below.

The third figure lets you push a Gaussian through a chain of invertible layers and see how mass is distributed. Each grid cell in the base space keeps its mass, and its density is that mass divided by its area, which changes from layer to layer.

InteractiveWarped grids, Jacobians and log-determinants
Base space: z∼N(0,I)\vb{z} \sim \Normal(\vb{0}, \mat{I}), equal cells
Data space after 3 layers: the same cells, warped
Each layer's contribution to log-determinant at the probe (bars) and cumulative sum (line)
−11123
  • cells: stronger color means higher density
  • bar: layer expands (log⁡∣det⁡∣>0\log\abs{\det}>0)
  • bar: layer contracts (log⁡∣det⁡∣<0\log\abs{\det}<0)
  • probe and its image
  • path through layers
Stacked layers
Color cells by
1.20
30°
0.20
log⁡pZ(z)\log p_Z(\vb{z}) at the probe−2.563
∑klog⁡∣det⁡Jk∣\sum_k \log\abs{\det J_k}0.594
log⁡pX(x)=log⁡pZ(z)−∑klog⁡∣det⁡Jk∣\log p_X(\vb{x}) = \log p_Z(\vb{z}) - \sum_k \log\abs{\det J_k}−3.157
Ellipse area / circle area1.786 (e^Σ = 1.811)
Cell mass: base → image0.9947 → 0.9952
On the left, z∼N(0,I)\vb{z} \sim \Normal(\vb{0}, \mat{I}) with equal cells; on the right, the same cells after stacking 1 to 8 layers (affine, planar and radial). Drag the probe: its small magenta circle becomes an ellipse whose area is e∑klog⁡∣det⁡Jk∣e^{\sum_k \log\abs{\det J_k}} times that of the circle, and the bars below show each layer's contribution. Edit a layer using the sliders: an affine layer always contributes the same amount, a planar one with s>0s > 0 expands near its line, and a radial one with β<0\beta < 0 contracts toward its center. Change the color to log⁡∣det⁡J∣\log\abs{\det J} and compare it with density: where cells contract, density rises.

What you should have seen:

  • Each cell’s mass stays the same; its area changes. The “cell mass” readings show that the sum of density times area remains ≈0.995\approx 0.995 (the Gaussian mass inside the square [−3,3]2[-3,3]^2) after any chain: the theorem is a conservation law.
  • Log-determinants add. The bars are each layer’s contributions at the probe and the line is their cumulative sum; the ellipse-to-circle area ratio is eΣe^{\Sigma} (with a small error only because the circle is not infinitesimal).
  • An affine layer is boring on purpose. Its Jacobian is constant, log⁡∣det⁡∣=a+b\log\abs{\det} = a + b in the figure, and all cells change area together. A flow’s power lies in nonlinear layers whose Jacobian depends on the point.
  • Density and volume compensate for each other. Where the log-determinant color indicates “contraction”, the corresponding density rises, and vice versa.

Composition: log-determinants add

A flow is a composition f=fL∘⋯∘f1f = f_L \circ \cdots \circ f_1 of layers, each a simple diffeomorphism. Write z0=z\vb{z}_0 = \vb{z} and zk=fk(zk−1)\vb{z}_k = f_k(\vb{z}_{k-1}), so x=zL\vb{x} = \vb{z}_L. The previous theorem applies to ff as a whole, but requires det⁡Jf\det\mat{J}_f, which the chain rule reduces to the layers.

Proof

The chain rule gives Jf(z0)=JfL(zL−1)⋯Jf1(z0)\mat{J}_f(\vb{z}_0) = \mat{J}_{f_L}(\vb{z}_{L-1})\cdots\mat{J}_{f_1}(\vb{z}_0). The determinant is multiplicative, so ∣det⁡Jf(z0)∣=∏k∣det⁡Jfk(zk−1)∣\abs{\det\mat{J}_f(\vb{z}_0)} = \prod_k \abs{\det\mat{J}_{f_k}(\vb{z}_{k-1})} and taking logarithms converts the product into a sum. Substitute into pX(x)=pZ(z0)/∣det⁡Jf(z0)∣p_{\vb{X}}(\vb{x}) = p_{\vb{Z}}(\vb{z}_0)/\abs{\det\mat{J}_f(\vb{z}_0)}. ■\blacksquare

∎

This formula is all that is needed to train a flow (Papamakarios et al., 2021): evaluate log⁡pX(xi)\log p_{\vb{X}}(\vb{x}_i) on the data, sum and maximize. To evaluate density, traverse the chain backwards (x→z0\vb{x} \to \vb{z}_0, hence “normalizing”); to sample, go forwards. A good layer therefore has a cheap inverse and a cheap log⁡∣det⁡∣\log\abs{\det}. A general determinant costs O(n3)\bigO(n^3), and in dimension n=104n = 10^4 that is prohibitive for every layer, data point and training step, so architectures are designed to make it trivial.

  • Diagonal or triangular. If J\mat{J} is triangular, det⁡J\det\mat{J} is the product of its diagonal and log⁡∣det⁡J∣=∑ilog⁡∣Jii∣\log\abs{\det\mat{J}} = \sum_i \log\abs{J_{ii}} costs O(n)\bigO(n). Autoregressive flows work this way: output ii depends only on inputs 1,…,i1, \dots, i.
  • Orthogonal. ∣det⁡∣=1\abs{\det} = 1: rotations and permutations contribute nothing to the log-determinant.
  • Rank-one update. The planar layer f(z)=z+u h(w⊤z+b)f(\vb{z}) = \vb{z} + \vb{u}\,h(\vb{w}\T\vb{z} + b) has J=I+h′(⋅) uw⊤\mat{J} = \mat{I} + h'(\cdot)\,\vb{u}\vb{w}\T, and the matrix determinant lemma gives det⁡J=1+h′(w⊤z+b) w⊤u\det\mat{J} = 1 + h'(\vb{w}\T\vb{z} + b)\,\vb{w}\T\vb{u}: a scalar instead of a n×nn\times n determinant. With h=tanh⁡h = \tanh it is invertible if w⊤u≥−1\vb{w}\T\vb{u} \ge -1 (Rezende and Mohamed, 2015), and is the one shown in the previous figure.
  • Coupling layers. Those used by RealNVP (Dinh et al., 2017) split the vector into two halves x=(xA,xB)\vb{x} = (\vb{x}_A, \vb{x}_B) and apply
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(\vb{s}(\vb{x}_A)\big) + \vb{t}(\vb{x}_A).

The Jacobian is block triangular,

J=[I0∂yB∂xAdiag⁡ ⁣(es(xA))],log⁡∣det⁡J∣=∑jsj(xA).\mat{J} = \begin{bmatrix} \mat{I} & \mat{0} \\ \pd{\vb{y}_B}{\vb{x}_A} & \diag\!\big(e^{\vb{s}(\vb{x}_A)}\big) \end{bmatrix}, \qquad \log\abs{\det \mat{J}} = \sum_j s_j(\vb{x}_A).

The block ∂yB∂xA\pd{\vb{y}_B}{\vb{x}_A} is a complicated dense matrix (it depends on the derivatives of networks s\vb{s} and t\vb{t}), but does not enter the determinant. And the inverse is xB=(yB−t(yA))⊙e−s(yA)\vb{x}_B = (\vb{y}_B - \vb{t}(\vb{y}_A)) \odot e^{-\vb{s}(\vb{y}_A)}: there is no need to invert the networks, only evaluate them. That is why s\vb{s} and t\vb{t} can be arbitrary multilayer perceptrons.

Sums of independent variables: convolution

Let XX and YY be independent with densities pXp_X and pYp_Y. What is the density of S=X+YS = X + Y? This is a change of variables with the auxiliary-variable trick: complete (X,Y)(X, Y) to the linear diffeomorphism (x,y)↦(x,s)=(x,x+y)(x, y) \mapsto (x, s) = (x, x + y), with matrix [1011]\begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix} and determinant one.

Proof

By independence, (X,Y)(X, Y) has joint density pX(x) pY(y)p_X(x)\,p_Y(y) (independence lesson). The transformation (x,y)↦(x,s)(x, y) \mapsto (x, s) has inverse (x,s)↦(x,s−x)(x, s) \mapsto (x, s - x) with determinant 11, so the pair (X,S)(X, S) has density pX(x) pY(s−x)p_X(x)\,p_Y(s - x). The marginal of SS is obtained by integrating over xx, justified by Fubini–Tonelli because the integrand is nonnegative. The discrete case uses the same argument with sums. ■\blacksquare

∎

Read the formula as an animation: reflect pYp_Y (y↦pY(−y)y \mapsto p_Y(-y)), slide it to position ss and calculate the area of the pointwise product. Convolution is commutative and associative, the mean and variance of the sum are the sums of the means and variances (expectation by linearity, variance by independence), and the support of the sum is the sum of the supports.

Convolution smooths: the density of the sum is at least as regular as the more regular of the two. The sum of two uniform variables is a continuous triangle, even though each has jumps, and the sum of three is already a piecewise parabola with a continuous derivative. The next figure shows this progression of shapes, anticipating the central limit theorem.

InteractiveConvolution as sliding, and its repetition
Above: pX(x)p_X(x) (blue), pY(s−x)p_Y(s - x) (orange) and their product (magenta). Below: pX+Yp_{X+Y}, the magenta area for each ss
  • pX(x)p_X(x)
  • pY(s−x)p_Y(s - x) (reflected)
  • product and its area
View
1.50
Shift ss1.50
pX+Y(s)=∫pX(x) pY(s−x) ⁣dxp_{X+Y}(s) = \int p_X(x)\,p_Y(s - x)\dd x0.1250
E[X+Y]\E[X+Y] (from the curve) and E[X]+E[Y]\E[X]+\E[Y]0.000 and 0.000
∫pX+Y\int p_{X+Y} (check)1.0000
In ‘Slide’, choose XX and YY and move ss (or press Play): the orange density is pY(s−x)p_Y(s - x) and the area of the magenta product is the value of pX+Yp_{X+Y} at ss, traced below. Uniform plus uniform gives a triangle. In ‘Repeat’, add nn independent copies of the same law and compare the standardized result with the bell curve: observe how skewness and kurtosis shrink, and that the uniform needs few copies while the exponential needs many more.

What you should have seen:

  • The product’s area is the height of the curve below. It is the formula, nothing more: the point sliding in the lower panel is at the height of that area.
  • A sum of variables with different tails inherits the worst of each. An exponential plus anything has infinite support on the right and an exponential tail.
  • Repeating moves the shape toward the bell. The more symmetric the starting law, the sooner it arrives: the uniform is already within a few hundredths with n=3n = 3, while the exponential, with skewness 22 and excess kurtosis 66, reduces them to 2/n2/\sqrt{n} and 6/n6/n.

Polar coordinates and Box–Muller

Polar coordinates (x,y)=(rcos⁡θ,rsin⁡θ)(x, y) = (r\cos\theta, r\sin\theta) are a diffeomorphism from (0,∞)×(0,2π)(0,\infty) \times (0, 2\pi) onto the plane without a half-axis, with Jacobian

J=[cos⁡θ−rsin⁡θsin⁡θrcos⁡θ],det⁡J=r.\mat{J} = \begin{bmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{bmatrix}, \qquad \det\mat{J} = r.

That factor rr is the area of the polar element r ⁣dr ⁣dθr\dd r\dd\theta, and with it we can finally evaluate the Gaussian normalizing integral:

(∫−∞∞e−x2/2 ⁣dx)2=∬R2e−(x2+y2)/2 ⁣dx ⁣dy=∫02π ⁣ ⁣∫0∞e−r2/2 r ⁣dr ⁣dθ=2π,\bigg(\int_{-\infty}^{\infty} e^{-x^2/2}\dd x\bigg)^{2} = \iint_{\R^2} e^{-(x^2 + y^2)/2}\dd x\dd y = \int_0^{2\pi}\!\!\int_0^{\infty} e^{-r^2/2}\,r\dd r\dd\theta = 2\pi,

hence ∫e−x2/2 ⁣dx=2π\int e^{-x^2/2}\dd x = \sqrt{2\pi} (Fubini–Tonelli in the first equality). But there is more: the same calculation gives the laws of RR and Θ\Theta when (Z1,Z2)∼iidN(0,1)(Z_1, Z_2) \iid \Normal(0, 1). Their density in (r,θ)(r, \theta) is the planar density multiplied by the Jacobian,

pR,Θ(r,θ)=12πe−r2/2⋅r=r e−r2/2⏟funcioˊn de r⋅12π⏟funcioˊn de θ,p_{R,\Theta}(r, \theta) = \frac{1}{2\pi}e^{-r^2/2}\cdot r = \underbrace{r\,e^{-r^2/2}}_{\text{función de } r}\cdot\underbrace{\frac{1}{2\pi}}_{\text{función de } \theta},

which factorizes: RR and Θ\Theta are independent, Θ\Theta is uniform on (0,2π)(0, 2\pi) and RR has tail P(R>r)=e−r2/2\Pr(R > r) = e^{-r^2/2}. Invert that tail using the inverse transform: U1=e−R2/2U_1 = e^{-R^2/2} is uniform on (0,1)(0, 1) (because P(U1≤u)=P(R2≥−2ln⁡u)=u\Pr(U_1 \le u) = \Pr(R^2 \ge -2\ln u) = u). Reversing the reasoning produces normals from uniforms.

Proof

This is a composition of two changes of variables; follow the mass of a tiny square. First (u1,u2)↦(r,θ)=(−2ln⁡u1, 2πu2)(u_1, u_2) \mapsto (r, \theta) = (\sqrt{-2\ln u_1},\,2\pi u_2) from (0,1)2(0,1)^2 to (0,∞)×(0,2π)(0,\infty)\times(0,2\pi). Its inverse is u1=e−r2/2u_1 = e^{-r^2/2}, u2=θ/(2π)u_2 = \theta/(2\pi), with diagonal Jacobian of determinant ∣−r e−r2/2∣⋅12π\abs{-r\,e^{-r^2/2}}\cdot\tfrac{1}{2\pi}, so pR,Θ(r,θ)=1⋅12π r e−r2/2p_{R,\Theta}(r,\theta) = 1\cdot\tfrac{1}{2\pi}\,r\,e^{-r^2/2}. Next (r,θ)↦(z1,z2)=(rcos⁡θ,rsin⁡θ)(r, \theta) \mapsto (z_1, z_2) = (r\cos\theta, r\sin\theta), with determinant rr, which divides the density: pZ1,Z2=pR,Θ/r=12πe−(z12+z22)/2p_{Z_1,Z_2} = p_{R,\Theta}/r = \tfrac{1}{2\pi}e^{-(z_1^2 + z_2^2)/2}. This is φ(z1) φ(z2)\varphi(z_1)\,\varphi(z_2), the product of two standard normals. ■\blacksquare

∎

The result has a particular beauty: the factor rr in the second step exactly compensates rr in the first. The area of a tiny square is multiplied overall by 2πer2/22\pi e^{r^2/2} and its density by the inverse, so density times area does not change. Check it.

InteractiveBox–Muller in polar coordinates: the Jacobian that balances everything
1. Square (u1,u2)(u_1, u_2): density 1
2. Radius and angle: r=−2ln⁡u1r = \sqrt{-2\ln u_1}, θ=2πu2\theta = 2\pi u_2
π2π
3. Plane (z1,z2)=(rcos⁡θ,rsin⁡θ)(z_1, z_2) = (r\cos\theta, r\sin\theta)
  • small square and points falling inside it
  • r=1r = 1
  • r=2r = 2
  • r=3r = 3 (circles: level sets of u1=e−r2/2u_1 = e^{-r^2/2})
  • θ=90°,180°,270°\theta = 90°, 180°, 270°
0.05
600
Areas: square → (r,θ)(r, \theta) → plane0.0100 → 0.1358 → 0.2114
∣det⁡J1∣=2π/(ru1)\abs{\det J_1} = 2\pi/(r u_1) and ∣det⁡J2∣=r\abs{\det J_2} = r13.50 and 1.552
Area ratio (measured) versus ∣det⁡J1∣∣det⁡J2∣=2πer2/2\abs{\det J_1}\abs{\det J_2} = 2\pi e^{r^2/2}21.1 versus 20.9
Density × area in each space0.0100, 0.0101, 0.0101
Drag the orange square around the (u1,u2)(u_1, u_2) square. In the second panel it becomes a rectangle in (r,θ)(r, \theta) (its width is multiplied by 1/(r u1)1/(r\,u_1) and its height by 2π2\pi), and in the third a curved sector of the plane. The readings compare the measured area ratio with 2πer2/22\pi e^{r^2/2} and show that density times area is the same in all three spaces. With u1u_1 close to 11 the radius is nearly 00 and the total area factor reaches its minimum value, 2π2\pi; with small u1u_1, the sector is huge. The points show how uniform samples in the square spread across the plane as a two-dimensional bell.

What you should have seen:

  • Each level set of u1u_1 is a circle. The three verticals in the first panel (the values u1=e−r2/2u_1 = e^{-r^2/2} for r=1,2,3r = 1, 2, 3) become straight lines in the second and circles in the third; the rays θ=90°,180°,270°\theta = 90°, 180°, 270° play the role of the horizontal lines.
  • Areas grow, mass does not. The measured area ratio and 2πer2/22\pi e^{r^2/2} agree, with a small error that increases with the size of the square; the third reading (density ×\times area) is the same in all three panels.
  • The center of the plane is nearly empty of uniform points. Few points have u1u_1 close to 11 (radii near zero), but those few spread over a tiny circle of area πr2\pi r^2: that is why the density at the origin, 1/(2π)1/(2\pi), is highest.

In practice, Box–Muller is not the most commonly used method today. Marsaglia’s polar variant avoids sines and cosines by accepting only points in a disk, and numpy.random.Generator.standard_normal uses the much faster ziggurat algorithm. Box–Muller remains the canonical example because its correctness is proved with a Jacobian, and because its structure is the pattern of “moving to coordinates where the law factorizes”.

Ratios and products: Cauchy, beta, Student’s tt

The same pattern (complete with an auxiliary variable, apply the Jacobian, integrate out the auxiliary) solves the other derived laws in the catalogue.

The gamma–beta relationship is the most fruitful example, which you prove in the first exercise: if X∼Gamma(a,1)X \sim \mathrm{Gamma}(a, 1) and Y∼Gamma(b,1)Y \sim \mathrm{Gamma}(b, 1) are independent, then U=X/(X+Y)∼Beta(a,b)U = X/(X + Y) \sim \mathrm{Beta}(a, b), V=X+Y∼Gamma(a+b,1)V = X + Y \sim \mathrm{Gamma}(a + b, 1), and U⊥ ⁣ ⁣ ⁣⊥VU \indep V. The surprising part is independence. It gives two constantly used facts: a sum of independent gammas with the same scale is gamma (a convolution solved without integrating), and a Dirichlet vector is sampled by normalizing independent gammas.

Using the same technique, if Z∼N(0,1)Z \sim \Normal(0,1) and V∼χν2V \sim \chi^2_\nu are independent, T=Z/V/νT = Z/\sqrt{V/\nu} has Student’s tt density,

pT(t)=Γ(ν+12)νπ  Γ(ν2)(1+t2ν)−(ν+1)/2.p_T(t) = \frac{\Gamma\big(\tfrac{\nu + 1}{2}\big)}{\sqrt{\nu\pi}\;\Gamma\big(\tfrac{\nu}{2}\big)}\Big(1 + \frac{t^2}{\nu}\Big)^{-(\nu + 1)/2}.

Obtain it by completing with VV and using Jacobian v/ν\sqrt{v/\nu}; the integral over vv is another gamma. With ν=1\nu = 1 this is the earlier Cauchy, and as ν→∞\nu \to \infty it tends to the normal.

Order statistics

Given a sample X1,…,Xn∼iidFX_1, \dots, X_n \iid F, its order statistics are its sorted values X(1)≤X(2)≤⋯≤X(n)X_{(1)} \le X_{(2)} \le \cdots \le X_{(n)}. X(1)X_{(1)} is the minimum, X(n)X_{(n)} the maximum, and X(k)X_{(k)} the kk-th smallest. They are not independent (they are ordered by construction), but their marginal law can be obtained without a double integral, by a counting argument.

The maximum is the simplest case: {X(n)≤x}\{X_{(n)} \le x\} happens if and only if all are ≤x\le x, and by independence

P(X(n)≤x)=F(x)n,P(X(1)>x)=(1−F(x))n.\Pr\big(X_{(n)} \le x\big) = F(x)^n, \qquad \Pr\big(X_{(1)} > x\big) = \big(1 - F(x)\big)^n.

The minimum of nn exponentials of rate λ\lambda satisfies P(X(1)>x)=e−nλx\Pr(X_{(1)} > x) = e^{-n\lambda x}: it is a Exp(nλ)\mathrm{Exp}(n\lambda). For the kk-th statistic, the key is an equivalence of events: the kk-th smallest is ≤x\le x if and only if at least kk of the variables are ≤x\le x. And the number of variables falling to the left of xx is a sum of nn independent indicators with probability F(x)F(x):

Nx=∑i=1n1[Xi≤x]∼Bin⁡(n,F(x)).N_x = \sum_{i=1}^{n}\ind[X_i \le x] \sim \Bin\big(n, F(x)\big).
Proof

The distribution formula is what we just argued. To differentiate it with respect to FF, use j(nj)=n(n−1j−1)j\binom{n}{j} = n\binom{n-1}{j-1} and (n−j)(nj)=n(n−1j)(n - j)\binom{n}{j} = n\binom{n-1}{j}:

 ⁣d ⁣dF[(nj)Fj(1−F)n−j]=n(n−1j−1)Fj−1(1−F)n−j−n(n−1j)Fj(1−F)n−j−1.\frac{\dd}{\dd F}\Big[\tbinom{n}{j}F^j(1-F)^{n-j}\Big] = n\tbinom{n-1}{j-1}F^{j-1}(1-F)^{n-j} - n\tbinom{n-1}{j}F^{j}(1-F)^{n-j-1}.

Summing over j=k,…,nj = k, \dots, n, the second term for each jj cancels the first for j+1j + 1, leaving only the first with j=kj = k (the second with j=nj = n has (n−1n)=0\binom{n-1}{n} = 0): n(n−1k−1)Fk−1(1−F)n−kn\binom{n-1}{k-1}F^{k-1}(1-F)^{n-k}. Multiply by F′=fF' = f (chain rule) and n(n−1k−1)=n!/((k−1)!(n−k)!)n\binom{n-1}{k-1} = n!/((k-1)!(n-k)!). ■\blacksquare

∎

It suffices to understand the uniform case. If FF is continuous, F(Xi)F(X_i) is uniform (probability integral transform) and, since F−1F\inv is increasing, X(k)=F−1(U(k))X_{(k)} = F\inv(U_{(k)}): all order statistics of a continuous law are an increasing transformation of those of uniforms. And with F(x)=xF(x) = x the density is n!(k−1)!(n−k)! xk−1(1−x)n−k\tfrac{n!}{(k-1)!(n-k)!}\,x^{k-1}(1-x)^{n-k}. Since B(k,n−k+1)=Γ(k)Γ(n−k+1)/Γ(n+1)=(k−1)!(n−k)!/n!B(k, n - k + 1) = \Gamma(k)\Gamma(n-k+1)/\Gamma(n+1) = (k-1)!(n-k)!/n!, it is exactly the density Beta(k,n−k+1)\mathrm{Beta}(k, n - k + 1). Its mean is k/(n+1)k/(n+1): the nn uniforms divide (0,1)(0,1) into n+1n + 1 gaps that are equal on average.

The same event equivalence, applied to uniforms, gives an identity from analysis without integrating anything.

Proof

Let U1,…,Un∼iidUnif⁡(0,1)U_1, \dots, U_n \iid \Unif(0, 1). The number NpN_p of them falling in [0,p][0, p] is Bin⁡(n,p)\Bin(n, p), and {U(k)≤p}={Np≥k}\{U_{(k)} \le p\} = \{N_p \ge k\}. Therefore P(Bin⁡(n,p)≥k)=P(U(k)≤p)\Pr(\Bin(n, p) \ge k) = \Pr(U_{(k)} \le p), and U(k)∼Beta(k,n−k+1)U_{(k)} \sim \mathrm{Beta}(k, n - k + 1) by the previous theorem. ■\blacksquare

∎

The final figure brings all three together: the ordered sample, the histogram of the kk-th statistic, and the two probabilities in the identity.

InteractiveThe kk-th of nn uniforms and the binomial tail
An ordered sample of n=7n = 7 uniforms. The kk-th (orange) is X(3)X_{(3)}
p = 0.40X(3) = 0.43
Histogram of X(3)X_{(3)} in 4000 samples versus Beta(3,5)\mathrm{Beta}(3, 5) density (line). Shaded area: P(Beta(3,5)≤p)\Pr(\mathrm{Beta}(3, 5) \le p)
  • simulated histogram of X(k)X_{(k)}
  • beta density
  • threshold pp and area to its left
7
3
Shortcuts
0.40
Points left of pp in this sample2 of 7
Does X(k)≤pX_{(k)} \le p occur? kk points are requiredno (2 < 3)
P(Bin(n,p)≥k)\Pr(\mathrm{Bin}(n, p) \ge k), exact0.580096
P(Beta(k,n−k+1)≤p)\Pr(\mathrm{Beta}(k, n-k+1) \le p), by integration0.580096
Fraction of 4000 samples with X(k)≤pX_{(k)} \le p0.5938
E[X(k)]=k/(n+1)\E[X_{(k)}] = k/(n+1) versus simulated mean0.3750 versus 0.3727
At the top, a sample of nn uniforms with the kk-th point in orange and threshold pp in magenta: count the points to the left. Below, the histogram of the kk-th in 4000 samples against the Beta(k,n−k+1)\mathrm{Beta}(k, n-k+1) density. Move pp: the two probabilities in the readings (the binomial tail, calculated with a sum, and the beta distribution function, calculated by integrating the density) agree in every decimal. Use the shortcuts to see the minimum (close to 00), median (centered) and maximum (close to 11).

What you should have seen:

  • The minimum approaches 00 and the maximum 11 as nn grows. Their means are 1/(n+1)1/(n+1) and n/(n+1)n/(n+1), and their densities are n(1−x)n−1n(1-x)^{n-1} and nxn−1n x^{n-1}.
  • The median concentrates. With k≈n/2k \approx n/2 the beta narrows around 1/21/2, with standard deviation of order 1/(2n)1/(2\sqrt{n}): that is why the sample median is a good estimator.
  • The two probabilities do not merely look alike; they are the same. One uses only a finite sum; the other, an integral. This identity makes scipy.stats.binom.sf and scipy.stats.beta.cdf return the same value.

Implementation from scratch

The cells check the results you have just proved. The first compares the change-of-variables formula against a simulation, including the non-injective case and the mistake of forgetting a branch.

[ ]Density of g(X): formula, simulation and the missing branchBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(0)
x = rng.standard_normal(400_000)

def hist_density(y, edges):
    counts, _ = np.histogram(y, bins=edges)
    return counts / (len(y) * np.diff(edges))

# 1) Y = exp(X): g inyectiva, p_Y(y) = p_X(log y) / y
edges = np.linspace(0.1, 6, 40)
mid = 0.5 * (edges[1:] + edges[:-1])
p_formula = stats.norm.pdf(np.log(mid)) / mid
p_sim = hist_density(np.exp(x), edges)
print("exp(X): máx |simulación - fórmula|    =", np.abs(p_sim - p_formula).max().round(4))
print("        máx |scipy.lognorm - fórmula| =", np.abs(stats.lognorm.pdf(mid, 1) - p_formula).max())

# 2) Y = X²: no inyectiva, se suman las dos preimágenes ±√y
edges = np.linspace(0.3, 6, 40)
mid = 0.5 * (edges[1:] + edges[:-1])
root = np.sqrt(mid)
p_formula = (stats.norm.pdf(root) + stats.norm.pdf(-root)) / (2 * root)
p_sim = hist_density(x**2, edges)
print("X²:     máx |simulación - fórmula|    =", np.abs(p_sim - p_formula).max().round(4))
print("        máx |chi2(1) de scipy - fórmula| =", np.abs(stats.chi2.pdf(mid, 1) - p_formula).max())

# 3) si se olvida la segunda preimagen, falta exactamente la mitad de la masa
p_una = stats.norm.pdf(root) / (2 * root)
print("una sola preimagen: cociente con la simulación =", (p_una / p_sim).mean().round(3))

Differences from the simulation are of order 10−210^{-2} or 10−310^{-3} (histogram noise, not an error in the theorem), and differences from SciPy are rounding: the lognormal and χ12\chi^2_1 are the formula. With only one preimage the ratio is 0.50.5, as theory says.

The second cell is the main laboratory: a normalizing flow in NumPy using the layers in this lesson, with their analytic log-determinants checked against the Jacobian’s numerical determinant. Each layer implements forward, inverse and log_abs_det_jacobian evaluated at its input. The planar layer is the one in the grid figure; its inverse has no closed form, but since x−z\vb{x} - \vb{z} is parallel to u\vb{u}, it suffices to solve a scalar increasing equation for α=w⊤z+b\alpha = \vb{w}\T\vb{z} + b, using bisection. Class Flow sums log-determinants while traversing the chain backwards, and log_prob is the previous section’s formula.

[ ]A normalizing flow from scratch: layers, log-determinants and exact densityBrowser
import numpy as np
import matplotlib.pyplot as plt

LOG2PI = np.log(2 * np.pi)

class Affine:
    """x = z·exp(a) + b por componentes. El jacobiano es diagonal: log|det| = Σ a_i."""
    def __init__(self, a, b):
        self.a, self.b = np.asarray(a, float), np.asarray(b, float)
    def forward(self, z): return z * np.exp(self.a) + self.b
    def inverse(self, x): return (x - self.b) * np.exp(-self.a)
    def log_abs_det_jacobian(self, z): return np.full(len(z), self.a.sum())

class Sinh:
    """x = sinh(z) por componentes: no lineal, con inversa arcsinh. log|det| = Σ log cosh(z_i)."""
    def forward(self, z): return np.sinh(z)
    def inverse(self, x): return np.arcsinh(x)
    def log_abs_det_jacobian(self, z): return np.log(np.cosh(z)).sum(axis=1)

class Rotation:
    """Giro de ángulo θ: ortogonal, así que |det| = 1 y la inversa es la traspuesta."""
    def __init__(self, theta):
        c, s = np.cos(theta), np.sin(theta)
        self.R = np.array([[c, -s], [s, c]])
    def forward(self, z): return z @ self.R.T
    def inverse(self, x): return x @ self.R
    def log_abs_det_jacobian(self, z): return np.zeros(len(z))

class Planar:
    """x = z + u·tanh(wᵀz + b) (Rezende y Mohamed): J = I + h'·u wᵀ, así que det J = 1 + h'(wᵀz + b)·wᵀu.
    Invertible si wᵀu > −1. La inversa no es explícita, pero se reduce a una ecuación escalar monótona."""
    def __init__(self, w, u, b):
        self.w, self.u, self.b = np.asarray(w, float), np.asarray(u, float), float(b)
        self.wu = float(self.w @ self.u)
        assert self.wu > -1, "con wᵀu ≤ −1 la capa deja de ser invertible"
    def forward(self, z): return z + np.outer(np.tanh(z @ self.w + self.b), self.u)
    def inverse(self, x):
        # α = wᵀz + b cumple wᵀx + b = α + wᵀu·tanh(α), creciente en α: bisección en [c − |wᵀu|, c + |wᵀu|]
        c = x @ self.w + self.b
        lo, hi = c - abs(self.wu) - 1e-9, c + abs(self.wu) + 1e-9
        for _ in range(60):
            mid = 0.5 * (lo + hi)
            below = mid + self.wu * np.tanh(mid) < c
            lo, hi = np.where(below, mid, lo), np.where(below, hi, mid)
        return x - np.outer(np.tanh(0.5 * (lo + hi)), self.u)
    def log_abs_det_jacobian(self, z):
        return np.log(np.abs(1 + (1 - np.tanh(z @ self.w + self.b) ** 2) * self.wu))

class Coupling:
    """Acoplamiento afín (RealNVP) en R²: la coordenada `cond` pasa intacta y decide la afín de la otra.
    Jacobiano triangular: log|det| = s(z_cond). La red que da s y t NUNCA se invierte."""
    def __init__(self, W1, W2, cond):
        self.W1, self.W2, self.cond, self.oth = W1, W2, cond, 1 - cond
    def _st(self, c):
        out = np.tanh(c @ self.W1) @ self.W2          # (n, 2)
        return np.tanh(out[:, :1]), out[:, 1:]         # s acotada en (-1, 1), t libre
    def forward(self, z):
        x = z.copy()
        s, t = self._st(z[:, [self.cond]])
        x[:, [self.oth]] = z[:, [self.oth]] * np.exp(s) + t
        return x
    def inverse(self, x):
        z = x.copy()
        s, t = self._st(x[:, [self.cond]])             # la coordenada cond no cambió: se recalculan s y t
        z[:, [self.oth]] = (x[:, [self.oth]] - t) * np.exp(-s)
        return z
    def log_abs_det_jacobian(self, z): return self._st(z[:, [self.cond]])[0][:, 0]

class Flow:
    """Base N(0, I) en R² seguida de una lista de capas, de z hacia x."""
    def __init__(self, layers): self.layers = layers
    def forward(self, z):
        ld = np.zeros(len(z))
        for layer in self.layers:
            ld += layer.log_abs_det_jacobian(z)        # el jacobiano se evalúa en la ENTRADA de la capa
            z = layer.forward(z)
        return z, ld
    def inverse(self, x):
        ld = np.zeros(len(x))
        for layer in reversed(self.layers):
            z = layer.inverse(x)
            ld += layer.log_abs_det_jacobian(z)
            x = z
        return x, ld
    def log_prob(self, x):
        z, ld = self.inverse(x)
        return -0.5 * (z**2).sum(axis=1) - LOG2PI - ld  # log p_X = log p_Z(z) - Σ log|det J_k|
    def sample(self, n, rng): return self.forward(rng.standard_normal((n, 2)))[0]

rng = np.random.default_rng(1)
flow = Flow([
    Affine([-0.6, -0.6], [0.0, 0.0]),
    Coupling(rng.normal(size=(1, 8)), rng.normal(size=(8, 2)), cond=0),
    Sinh(),
    Planar([1.2, -0.6], [0.7, 0.5], 0.3),
    Rotation(0.6),
    Coupling(rng.normal(size=(1, 8)), rng.normal(size=(8, 2)), cond=1),
    Affine([0.2, -0.1], [0.5, -0.3]),
])

# 1) la inversa deshace a la directa
z = rng.standard_normal((1000, 2))
x, _ = flow.forward(z)
print("ida y vuelta: error máximo =", np.abs(flow.inverse(x)[0] - z).max())

# 2) el log-det analítico frente al determinante numérico del jacobiano (diferencias finitas centradas)
def numeric_logdet(f, z, eps=1e-6):
    J = np.zeros((2, 2))
    for j in range(2):
        e = np.zeros((1, 2)); e[0, j] = eps
        J[:, j] = (f(z + e) - f(z - e))[0] / (2 * eps)
    return np.linalg.slogdet(J)[1]
errs = [abs(flow.forward(zi[None])[1][0] - numeric_logdet(lambda q: flow.forward(q)[0], zi[None])) for zi in z[:200]]
print("log|det J|: error máximo analítico frente a numérico =", max(errs))

# 3) la densidad integra 1 (suma de Riemann en una rejilla)
g = np.linspace(-10, 10, 321)
X, Y = np.meshgrid(g, g)
pts = np.column_stack([X.ravel(), Y.ravel()])
dens = np.exp(flow.log_prob(pts)).reshape(X.shape)
h = g[1] - g[0]
print("∫ p_X dx ≈", round(dens.sum() * h * h, 4), "(el resto está en las colas, fuera de la rejilla)")

# 4) log_prob en la dirección inversa frente a la directa, calculada con los z originales
x, ld = flow.forward(z)
print("log_prob(x) frente a la dirección directa: error máximo =", np.abs(flow.log_prob(x) - (-0.5 * (z**2).sum(1) - LOG2PI - ld)).max())

fig, ax = plt.subplots(1, 2, figsize=(9, 3.6))
ax[0].contourf(X, Y, dens, 14, cmap="Blues")
ax[0].set_title("densidad exacta $p_X$ (cambio de variables)")
xs = flow.sample(3000, rng)
ax[1].scatter(xs[:, 0], xs[:, 1], s=2, alpha=0.4)
ax[1].set_title("3000 muestras $x = f(z)$")
for a in ax:
    a.set_xlim(-5, 5); a.set_ylim(-5, 5); a.set_aspect("equal")
plt.tight_layout()

What matters about the cell is what it does not do: it computes no matrix determinant except in the numerical check. The four checks close the theorem’s loop. The round trip, analytical versus numerical log-det, and normalization to ≈1\approx 1 (less the tail outside the grid) are precisely what the hypotheses guarantee: bijectivity, differentiability and the Jacobian formula at each layer’s input. And the samples flow.sample (forward direction) and exact density flow.log_prob (inverse direction) describe the same law, making the model useful. Training this flow by maximizing ∑ilog⁡pX(xi)\sum_i \log p_X(\vb{x}_i) is left for the generative-models module (normalizing flows, coupling layers).

The third cell implements Box–Muller and its polar variant and checks the properties asserted by the theorem: normality, independence (the correlation of squares, the test that truly distinguishes “uncorrelated” from “independent”), the law of R2R^2 and Marsaglia’s acceptance rate π/4\pi/4.

[ ]Box–Muller from scratch and its polar variantBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(7)

def box_muller(n, rng):
    u1 = 1.0 - rng.random(n)            # en (0, 1]: así log(u1) nunca es log(0)
    u2 = rng.random(n)
    r = np.sqrt(-2.0 * np.log(u1))
    t = 2.0 * np.pi * u2
    return np.stack([r * np.cos(t), r * np.sin(t)], axis=1)

z = box_muller(200_000, rng)
print("medias:", z.mean(axis=0).round(3), " covarianza:\n", np.cov(z.T).round(3))
print("KS de cada columna frente a N(0,1): p-valores", [round(float(stats.kstest(z[:, j], "norm").pvalue), 3) for j in range(2)])
print("KS de R² frente a chi2(2):          p-valor ", round(float(stats.kstest((z**2).sum(axis=1), "chi2", args=(2,)).pvalue), 3))
print("corr(Z1², Z2²) =", np.corrcoef(z[:, 0]**2, z[:, 1]**2)[0, 1].round(4), "(0 si son independientes; con Z2 = |Z1| saldría 1)")

def marsaglia(n, rng):
    """Versión polar: sin senos ni cosenos, a cambio de rechazar los puntos fuera del disco unidad."""
    out, tried, kept = [], 0, 0
    while kept < n:
        v = rng.uniform(-1, 1, size=(n, 2))
        s = (v**2).sum(axis=1)
        ok = (s > 0) & (s < 1)
        out.append(v[ok] * np.sqrt(-2.0 * np.log(s[ok]) / s[ok])[:, None])
        tried += n
        kept += int(ok.sum())
    return np.concatenate(out)[:n], kept / tried

w, acc = marsaglia(100_000, rng)
print("Marsaglia: aceptación =", round(acc, 3), " frente a π/4 =", round(np.pi / 4, 3), "; KS p =", round(float(stats.kstest(w[:, 0], "norm").pvalue), 3))

The pp-values should not be small (with a fixed seed they are reproducible), and correlation between Z12Z_1^2 and Z22Z_2^2 is zero up to noise of order 1/n1/\sqrt{n}. Marsaglia’s variant does the same without trigonometry: if (V1,V2)(V_1, V_2) is uniform in the unit disk and S=V12+V22S = V_1^2 + V_2^2, then SS is uniform on (0,1)(0,1) and the angle is uniform and independent, so (V1,V2)−2ln⁡S/S(V_1, V_2)\sqrt{-2\ln S/S} has the Box–Muller law without evaluating sines or cosines; the acceptance rate π/4\pi/4 is the ratio of disk to square areas.

The fourth cell checks convolution and compares with closed-form formulas. Discrete convolution is np.convolve, which is O(n2)\bigO(n^2); on a very fine grid scipy.signal.fftconvolve is preferable, using the FFT.

[ ]Numerical convolution: exponentials, uniforms and PoissonBrowser
import numpy as np
from scipy import stats

h = 0.002
t = np.arange(0, 14, h)

# Exp(1) + Exp(2): la convolución numérica frente a la fórmula cerrada 2(e^-t - e^-2t)
fx, fy = np.exp(-t), 2 * np.exp(-2 * t)
conv = np.convolve(fx, fy)[: len(t)] * h
exact = 2 * (np.exp(-t) - np.exp(-2 * t))
print("Exp(1)+Exp(2): máx |convolución - exacta| =", np.abs(conv - exact).max().round(5), "  p(1) =", conv[int(1 / h)].round(4), "  exacta =", exact[int(1 / h)].round(4))

# suma de uniformes (Irwin-Hall): tres convoluciones de la densidad de U(0,1)
tt = np.arange(0, 3, h)
u = (tt < 1).astype(float)
s2 = np.convolve(u, u)[: len(tt)] * h
s3 = np.convolve(s2, u)[: len(tt)] * h
def ih3_exact(x):  # x²/2 en [0,1]; (-2x²+6x-3)/2 en [1,2]; (3-x)²/2 en [2,3]
    return np.where(x < 1, x**2 / 2, np.where(x < 2, (-2 * x**2 + 6 * x - 3) / 2, (3 - x) ** 2 / 2))
print("U+U+U: máx |convolución - Irwin-Hall| =", np.abs(s3 - ih3_exact(tt)).max().round(4))
print("       máx |U+U+U - N(1.5, 1/4)|     =", np.abs(s3 - stats.norm.pdf(tt, 1.5, 0.5)).max().round(4), f" (el pico vale {s3.max():.3f} frente a {stats.norm.pdf(0, 0, 0.5):.3f}: con tres sumandos ya parece una campana)")

# pmf: la suma de Poisson independientes es Poisson, por convolución de las funciones de masa
k = np.arange(0, 60)
pm = np.convolve(stats.poisson.pmf(k, 2.0), stats.poisson.pmf(k, 3.0))[: len(k)]
print("Poisson(2)+Poisson(3): máx |pmf convolucionada - Poisson(5)| =", np.abs(pm - stats.poisson.pmf(k, 5.0)).max())

# la suma de variables DEPENDIENTES no se obtiene convolucionando: X + X no es X + X' con X' independiente
x = np.random.default_rng(0).uniform(0, 1, 200_000)
print("Var(X + X) =", np.var(x + x).round(4), " (4 Var X = 1/3);  Var(X + X') =", np.var(x + np.random.default_rng(1).uniform(0, 1, 200_000)).round(4), " (2 Var X = 1/6)")

The error ≈4⋅10−3\approx 4\cdot 10^{-3} in the first comparison comes from the Riemann rule itself (order hh), not the theorem; halving hh halves it. For pmfs, by contrast, convolution is exact: sums are finite, and the error is rounding.

The fifth cell checks order statistics: the binomial–beta identity using SciPy, the beta law of the kk-th statistic, the expected maximum, and the Gumbel-max trick.

[ ]Order statistics, binomial–beta identity and Gumbel-maxBrowser
import numpy as np
from scipy import stats

rng = np.random.default_rng(3)
n, k, p = 10, 4, 0.3

# la identidad: P(Bin(n, p) >= k) = P(Beta(k, n-k+1) <= p)
print("P(Bin(10, 0.3) >= 4)       =", stats.binom.sf(k - 1, n, p))
print("P(Beta(4, 7) <= 0.3)       =", stats.beta.cdf(p, k, n - k + 1))

# el k-ésimo menor de n uniformes simulado
u = np.sort(rng.random((200_000, n)), axis=1)
kth = u[:, k - 1]
print("E[X_(4)] = k/(n+1) =", round(k / (n + 1), 4), " simulado:", kth.mean().round(4), "; KS frente a Beta(4, 7): p =", round(float(stats.kstest(kth, "beta", args=(k, n - k + 1)).pvalue), 3))
print("E[máximo de 10 uniformes] = n/(n+1) =", round(n / (n + 1), 4), " simulado:", u[:, -1].mean().round(4))
print("P(mínimo > 0.1) = 0.9^10 =", round(0.9**10, 4), " simulado:", (u[:, 0] > 0.1).mean().round(4))

# cualquier ley continua: X_(k) = F^{-1}(U_(k)). Máximo de 5 exponenciales: F_max(x) = (1 - e^-x)^5
m = rng.exponential(size=(200_000, 5)).max(axis=1)
x0 = 2.0
print("P(máx de 5 Exp(1) <= 2) =", round((1 - np.exp(-x0)) ** 5, 4), " simulado:", (m <= x0).mean().round(4))

# truco de Gumbel-max: argmax(logits + G) con G = -log(-log U) muestrea de softmax(logits)
logits = np.log([0.5, 0.3, 0.15, 0.05])
g = -np.log(-np.log(rng.random((400_000, 4))))
freq = np.bincount(np.argmax(logits + g, axis=1), minlength=4) / 400_000
print("frecuencias Gumbel-max:", freq.round(3), " frente a softmax:", np.exp(logits).round(3))

The first two lines agree to the last decimal, as the theorem says (this is not an approximation). The rest check the section’s formulas: the kk-th statistic is beta, the mean of the maximum is n/(n+1)n/(n+1), and the maximum of nonuniform variables is obtained from FnF^n.

Using libraries

The affine relationship in the multivariate section, using SciPy. The cell computes log⁡pY(y)\log p_{\vb{Y}}(\vb{y}) of Y=AX+b\vb{Y} = \mat{A}\vb{X} + \vb{b} in two ways and shows why slogdet is used: the determinant of an upper triangular matrix with 500500 factors 55 on the diagonal overflows.

[ ]Affine change of variables with SciPy, and why slogdetBrowser
import numpy as np
from scipy.stats import multivariate_normal as mvn

rng = np.random.default_rng(0)

# Y = A X + b con X ~ N(0, I): log p_Y(y) = log p_X(A^-1 (y - b)) - log|det A|
d = 3
A = rng.normal(size=(d, d)) + 2 * np.eye(d)
b = rng.normal(size=d)
y = rng.normal(size=d)
x = np.linalg.solve(A, y - b)                       # A^-1 (y - b), sin formar la inversa
sign, logabsdet = np.linalg.slogdet(A)
lp_formula = mvn(np.zeros(d)).logpdf(x) - logabsdet
lp_scipy = mvn(mean=b, cov=A @ A.T).logpdf(y)        # la ley N(b, A Aᵀ) que scipy conoce
print("log p_Y(y) por cambio de variables:", round(lp_formula, 8))
print("log p_Y(y) con N(b, A Aᵀ) de scipy:", round(lp_scipy, 8))

# el determinante desborda en dimensión alta; slogdet no
n = 500
M = 5 * np.eye(n) + 0.05 * np.triu(rng.normal(size=(n, n)), 1)
sign, ld = np.linalg.slogdet(M)
with np.errstate(over="ignore"):
    det = np.linalg.det(M)
print(f"n = {n}:  det(M) = {det}   slogdet = ({sign:+.0f}, {ld:.3f})   (n log 5 = {n * np.log(5):.3f})")

The first two lines match because they are the same formula, one with the explicit Jacobian and the other with covariance AA⊤\mat{A}\mat{A}\T. In the third, det gives inf, while slogdet returns the correct logarithm, nln⁡5n\ln 5 (a triangular determinant is the product of its diagonal).

PyTorch provides the pieces of a flow in torch.distributions: TransformedDistribution applies a list of Transform to a base distribution and computes log_prob exactly as in the composition theorem. This cell, which runs on CPU with minimal sizes, reproduces a lognormal and a logit-normal with PyTorch transformations and checks log_prob against the hand formula and the log-determinant against the autograd Jacobian.

[ ]TransformedDistribution and log-determinants in PyTorch (CPU)Local GPU
import torch
from torch.distributions import Independent, Normal, TransformedDistribution, AffineTransform, ExpTransform, SigmoidTransform

torch.manual_seed(0)
loc, scale = torch.tensor([0.5, -0.5]), torch.tensor([1.5, 0.7])
base = Independent(Normal(torch.zeros(2), torch.ones(2)), 1)          # N(0, I) en R², un evento = un vector

# dos cadenas: z -> exp(scale·z + loc) (lognormal multivariante) y z -> sigmoide(scale·z + loc) (logit-normal)
lognormal = TransformedDistribution(base, [AffineTransform(loc, scale), ExpTransform()])
logitnormal = TransformedDistribution(base, [AffineTransform(loc, scale), SigmoidTransform()])

x = lognormal.sample((4,))
z = (torch.log(x) - loc) / scale                                       # la inversa, a mano
manual = base.log_prob(z) - torch.log(scale).sum() - torch.log(x).sum(dim=-1)   # log p_Z(z) - Σ log|det J_k|
print("lognormal: log_prob de torch frente a la fórmula a mano, máx |dif| =", (lognormal.log_prob(x) - manual).abs().max().item())

# el log-det de torch frente al determinante del jacobiano calculado por autograd
affine, sig = logitnormal.transforms
y = logitnormal.sample((3,))
for yi in y:
    zi = affine.inv(torch.logit(yi))
    J = torch.autograd.functional.jacobian(lambda q: torch.sigmoid(q * scale + loc), zi)
    ld_auto = torch.linalg.slogdet(J)[1]
    w = zi * scale + loc
    ld_torch = affine.log_abs_det_jacobian(zi, w).sum() + sig.log_abs_det_jacobian(w, yi).sum()
    print(f"logit-normal: log|det J| autograd = {ld_auto.item():+.6f}   transformaciones de torch = {ld_torch.item():+.6f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The difference in float32 is 10−710^{-7}, the accuracy of single precision. Each PyTorch Transform implements exactly the contract of our layers: forward, inverse (_inverse) and log_abs_det_jacobian.

Common mistakes

Exercises

ProofGamma, beta and independence
Prove: Let X∼Gamma(a,1)X \sim \mathrm{Gamma}(a, 1) and Y∼Gamma(b,1)Y \sim \mathrm{Gamma}(b, 1) be independent. Then U=X/(X+Y)∼Beta(a,b)U = X/(X + Y) \sim \mathrm{Beta}(a, b), V=X+Y∼Gamma(a+b,1)V = X + Y \sim \mathrm{Gamma}(a + b, 1) and UU and VV are independent.
0
The density of Gamma(a,1)\mathrm{Gamma}(a, 1) is xa−1e−x/Γ(a)x^{a-1}e^{-x}/\Gamma(a) on (0,∞)(0, \infty), and that of Beta(a,b)\mathrm{Beta}(a, b) is ua−1(1−u)b−1/B(a,b)u^{a-1}(1-u)^{b-1}/B(a, b) on (0,1)(0, 1), with B(a,b)=Γ(a)Γ(b)/Γ(a+b)B(a, b) = \Gamma(a)\Gamma(b)/\Gamma(a+b).

Step 1 of 5. What is the joint density of (X,Y)(X, Y) and where should you start?

ProofThe square of a normal
Prove: If X∼N(0,1)X \sim \Normal(0, 1), then Y=X2Y = X^2 has density pY(y)=e−y/22πyp_Y(y) = \dfrac{e^{-y/2}}{\sqrt{2\pi y}} on y>0y > 0, that is, Y∼χ12=Gamma(12,escala 2)Y \sim \chi^2_1 = \mathrm{Gamma}(\tfrac12, \text{escala } 2).
0
Use φ(x)=e−x2/2/2π\varphi(x) = e^{-x^2/2}/\sqrt{2\pi} and Γ(1/2)=π\Gamma(1/2) = \sqrt{\pi}.

Step 1 of 4. g(x)=x2g(x) = x^2 is not injective on R\R. How do you proceed?

NumericThe maximum of ten uniforms
Let U1,…,U10∼iidUnif⁡(0,1)U_1, \dots, U_{10} \iid \Unif(0, 1). Calculate E[max⁡iUi]\E[\max_i U_i].
QuizThe log-density of AX + b
Let Y=AX+b\vb{Y} = \mat{A}\vb{X} + \vb{b} with A\mat{A} invertible and X\vb{X} with density pXp_{\vb{X}}. What is log⁡pY(y)\log p_{\vb{Y}}(\vb{y})?
NumericA lognormal density
Let X∼N(0,1)X \sim \Normal(0, 1) and Y=eXY = e^X. Calculate pY(2)p_Y(2).
NumericA beta distribution function without integration
Calculate P(Beta(4,7)≤0.3)\Pr\big(\mathrm{Beta}(4, 7) \le 0.3\big) without integrating the beta density.
NumericThe sum of two exponentials
Let X∼Exp(1)X \sim \mathrm{Exp}(1) and Y∼Exp(2)Y \sim \mathrm{Exp}(2) be independent (rates 1 and 2). Calculate the density of X+YX + Y at s=1s = 1.
QuizA coupling layer
In the affine coupling layer yA=xA\vb{y}_A = \vb{x}_A, yB=xB⊙es(xA)+t(xA)\vb{y}_B = \vb{x}_B \odot e^{\vb{s}(\vb{x}_A)} + \vb{t}(\vb{x}_A), with s\vb{s} and t\vb{t} arbitrary neural networks, which statements are true?

More than one answer may be correct.

QuizWhen is it a convolution?
In which case is the density of X+YX + Y the convolution pX∗pYp_X * p_Y of the marginal densities?
NumericHow much a tiny square stretches in Box–Muller
In the Box–Muller transform, a tiny square in the (u1,u2)(u_1, u_2) plane at point u1=e−2u_1 = e^{-2} moves to the (z1,z2)(z_1, z_2) plane. By what factor is its area multiplied?
Codelog_prob of a composed transformation
Implement flow_log_prob(layers, x, base_logpdf). layers is a list of layers in the order z→x\vb{z} \to \vb{x}, each with methods forward(z), inverse(x) and log_abs_det_jacobian(z), which returns an array of shape (n,) with log⁡∣det⁡J∣\log\abs{\det\mat{J}} evaluated at the layer's input $\vb{z}$ (arrays of shape (n, d)). x is an array (n, d) and base_logpdf(z) returns (n,) with log⁡pZ\log p_{\vb{Z}}. The function must return log⁡pX(x)=log⁡pZ(z0)−∑klog⁡∣det⁡Jfk(zk−1)∣\log p_{\vb{X}}(\vb{x}) = \log p_{\vb{Z}}(\vb{z}_0) - \sum_k \log\abs{\det\mat{J}_{f_k}(\vb{z}_{k-1})}. Tests compare it with the analytical density of an affine transformation, a lognormal and the numerical Jacobian determinant of a chain.
import numpy as np

def flow_log_prob(layers, x, base_logpdf):
  # recorre las capas al revés: z = capa.inverse(x), acumula log|det J| en la entrada de la capa
  pass
Shift+Enter to run

Summary

Key idea
Transforming a random variable transports mass: the density of Y=g(X)\vb{Y} = g(\vb{X}) is that of X\vb{X} at the origin point, divided by the factor ∣det⁡Jg∣\abs{\det\mat{J}_g} by which gg stretches volume, and summed over all preimages if gg is not injective. This single formula yields exact flow log-densities (layer log-determinants add), convolution (a change of variables with Jacobian 1), Box–Muller and the gamma–beta relationship (coordinate changes that factorize the law), and order-statistic laws.
  • One dimension: pY(y)=pX(g−1(y)) ∣(g−1)′(y)∣p_Y(y) = p_X(g\inv(y))\,\abs{(g\inv)'(y)} for gg C1C^1 and monotone. Density dilutes where gg stretches and accumulates where it compresses. For non-injective gg, sum contributions pX(x)/∣g′(x)∣p_X(x)/\abs{g'(x)} over all preimages; integrable singularities appear at critical values.
  • Several dimensions: pY(y)=pX(x)/∣det⁡Jg(x)∣p_{\vb{Y}}(\vb{y}) = p_{\vb{X}}(\vb{x})/\abs{\det\mat{J}_g(\vb{x})} with x=g−1(y)\vb{x} = g\inv(\vb{y}). The determinant is the local volume-change factor; in the affine case, log⁡pY(y)=log⁡pX(A−1(y−b))−log⁡∣det⁡A∣\log p_{\vb{Y}}(\vb{y}) = \log p_{\vb{X}}(\mat{A}\inv(\vb{y}-\vb{b})) - \log\abs{\det\mat{A}}.
  • Composition: log⁡pX(x)=log⁡pZ(z0)−∑klog⁡∣det⁡Jfk(zk−1)∣\log p_{\vb{X}}(\vb{x}) = \log p_{\vb{Z}}(\vb{z}_0) - \sum_k\log\abs{\det\mat{J}_{f_k}(\vb{z}_{k-1})}, evaluating each determinant at its layer’s input. Use structures with cheap determinants (triangular, rank one, coupling) and slogdet instead of det.
  • Sums of independents: the density of X+YX + Y is convolution ∫pX(x) pY(s−x) ⁣dx\int p_X(x)\,p_Y(s - x)\dd x (Jacobian 11 and marginalization); means and variances add, and repeated convolution approaches the bell.
  • Polar coordinates and Box–Muller: with Jacobian rr, the two variables −2ln⁡U1cos⁡2πU2\sqrt{-2\ln U_1}\cos 2\pi U_2 and −2ln⁡U1sin⁡2πU2\sqrt{-2\ln U_1}\sin 2\pi U_2 are independent normals. The ratio of normals is Cauchy, and the gamma–beta relationship gives beta, Dirichlet and χ2\chi^2.
  • Order statistics: P(X(k)≤x)=P(Bin⁡(n,F(x))≥k)\Pr(X_{(k)} \le x) = \Pr(\Bin(n, F(x)) \ge k); for uniforms, U(k)∼Beta(k,n−k+1)U_{(k)} \sim \mathrm{Beta}(k, n-k+1), giving P(Bin⁡(n,p)≥k)=P(Beta(k,n−k+1)≤p)\Pr(\Bin(n,p) \ge k) = \Pr(\mathrm{Beta}(k, n-k+1) \le p).