Course contents 07 / 22

07 / 22 · Random Variables

Functions of random variables

Track probability through squaring, clipping, inverse sampling and an invertible flow. Count valid preimages, derive densities and check when a continuous input creates an atom.

On this page 6

An error can be positive or negative; its square is always nonnegative. Squaring merges outcomes, so a density cannot be transformed by simply squaring its horizontal coordinate. We have to track the probability carried by every input that reaches the same output.

The continuous-distributions lesson describes probability as area. For a measurable transformation Y=g(X)Y=g(X), that area follows the event back to the input:

Pr⁡(Y∈B)=Pr⁡(X∈g−1(B)).\Pr(Y\in B)=\Pr\bigl(X\in g^{-1}(B)\bigr).

Here g−1(B)g^{-1}(B) means the set of preimages, even when gg has no inverse function. This event identity is the starting point for the discrete and continuous calculations below; see Siegrist’s transformation theory.

The discrete case#

Take a deliberately small distribution:

xx−3-3−1-11133
Pr⁡(X=x)\Pr(X=x)1/81/83/83/81/41/41/41/4

For Y=X2Y=X^2, the two input outcomes at each magnitude merge. They are disjoint events, so their masses add:

Pr⁡(Y=1)=38+14=58,Pr⁡(Y=9)=18+14=38.\begin{aligned} \Pr(Y=1)&=\frac38+\frac14=\frac58,\\ \Pr(Y=9)&=\frac18+\frac14=\frac38. \end{aligned}

The general rule is a sum over all inputs with the requested output:

pY(y)=∑x: g(x)=ypX(x).p_Y(y)=\sum_{x:\,g(x)=y}p_X(x).

There is no derivative here. A discrete probability belongs to a point; we only collect points into groups. In particular, retaining just the positive square root would lose probability.

The distribution function method#

Now let XX be uniform on [−2,4][-2,4], still with Y=X2Y=X^2. The input interval has length 66, so an input event has probability equal to its length divided by 66.

For a nonnegative threshold yy, the event X2≤yX^2\le y asks for the part of the symmetric interval that remains inside the input support:

{X2≤y}={X∈[−y,y]∩[−2,4]}.\{X^2\le y\}=\{X\in[-\sqrt y,\sqrt y]\cap[-2,4]\}.

Until y=4y=4, both ends move. After that, the left end is fixed at −2-2; only the positive end continues to move. Thus

FY(y)={0,y<0,y/3,0≤y≤4,(y+2)/6,4<y≤16,1,y>16.F_Y(y)= \begin{cases} 0,&y<0,\\ \sqrt y/3,&0\le y\le4,\\ (\sqrt y+2)/6,&4<y\le16,\\ 1,&y>16. \end{cases}

This immediately gives two checkable probabilities:

Pr⁡(Y≤1)=13,Pr⁡(4<Y≤9)=16.\begin{aligned} \Pr(Y\le1)&=\frac13,\\ \Pr(4<Y\le9)&=\frac16. \end{aligned}

For the first, the input interval is [−1,1][-1,1], length 22. For the second, only (2,3](2,3] remains in the input support; the negative interval would lie below −2-2. These event calculations check the CDF without differentiating anything.

Figure

One or two valid branches

Squaring on the input supportThe parabola is drawn only from minus two to four. Level one intersects at minus one and one; level nine intersects only at three.04916-2024y = x²xThe CDF of the squareThe CDF rises from zero to one between zero and sixteen. At y = 4 it equals two thirds; a single branch applies thereafter.00.5104916F(y)y
The input is uniform on [−2, 4]. At y = 1 there are two roots; at y = 9 only one remains in the support. The CDF is continuous at y = 4 although its slope changes.

Differentiating on the two open pieces gives a density:

fY(y)={1/(6y),0<y<4,1/(12y),4<y<16,0,otherwise.f_Y(y)= \begin{cases} 1/(6\sqrt y),&0<y<4,\\ 1/(12\sqrt y),&4<y<16,\\ 0,&\text{otherwise}. \end{cases}

Its value at the individual endpoints can be assigned any nonnegative value without changing probabilities. The density grows without bound near zero, but the CDF has no jump there: Pr⁡(Y=0)=0\Pr(Y=0)=0. An infinite limiting density is not a point mass. At 44 the density changes because one branch ends; the CDF remains continuous.

The change-of-variables formula#

Suppose XX has a density on an interval. If gg on that interval is continuously differentiable, strictly monotone and has nonzero derivative, let hh be its inverse. For an increasing map we have FY(y)=FX(h(y))F_Y(y)=F_X(h(y)). Differentiating gives fX(h(y))h′(y)f_X(h(y))h'(y). A decreasing map reverses the event inequality and the derivative sign. Both cases give

fY(y)=fX(h(y)) ∣h′(y)∣.f_Y(y)=f_X(h(y))\,|h'(y)|.

At y=g(x)y=g(x) this is equivalently

fY(g(x))=fX(x)∣g′(x)∣.f_Y(g(x))=\frac{f_X(x)}{|g'(x)|}.

The derivative accounts for the change in interval length. If a small interval doubles in width, its density halves so that its probability stays the same. These assumptions and the absolute derivative are the ones checked in Siegrist’s change-of-variables theorem.

For example, keep X∼Uniform⁡[−2,4]X\sim\operatorname{Uniform}[-2,4] and set V=5−2XV=5-2X. The range is [−3,9][-3,9], of length 1212. The inverse derivative is −1/2-1/2, so fV(v)=1/12f_V(v)=1/12 inside this range. Omitting the absolute value would produce a negative density.

If the input support splits into finitely many such monotone branches, sum the branch densities at a regular output value:

fY(y)=∑x: g(x)=yfX(x)∣g′(x)∣.f_Y(y)=\sum_{x:\,g(x)=y}\frac{f_X(x)}{|g'(x)|}.

Only roots inside the input support belong in the sum. For the square example, each root contributes 1/(12y)1/(12\sqrt y). There are two roots below 44 and one above 44. The formula applies away from the zero derivative at x=0x=0; the CDF already settles what happens there.

An invertible positive transformation gives another useful distribution. Let T∼N(μ,σ2)T\sim\mathcal N(\mu,\sigma^2), with σ>0\sigma>0, and set L=eTL=e^T. Its inverse is log⁡l\log l, with derivative 1/l1/l, so for l>0l>0 we obtain the log-normal density:

fL(l)=1lσ2πexp⁡[−(log⁡l−μ)22σ2].f_L(l)=\frac{1}{l\sigma\sqrt{2\pi}} \exp\left[-\frac{(\log l-\mu)^2}{2\sigma^2}\right].

It is zero for nonpositive ll. Choose μ=log⁡2\mu=\log2 and σ=1/2\sigma=1/2. The median is 22 because half of the normal mass is below its mean. At that median the density is

fL(2)=12π≈0.398942.f_L(2)=\frac{1}{\sqrt{2\pi}}\approx0.398942.

This is a density value, not a probability of observing exactly 22.

Inverse transform sampling#

The CDF describes how much mass lies below a threshold. Reversing that question turns a uniform probability level into an outcome. For any real-valued CDF FF, define the generalized quantile for 0<u<10<u<1 by

Q(u)=inf⁡{y:F(y)≥u}.Q(u)=\inf\{y:F(y)\ge u\}.

The defining relation is Q(u)≤yQ(u)\le y exactly when u≤F(y)u\le F(y). If U∼Uniform⁡(0,1)U\sim\operatorname{Uniform}(0,1), then

Pr⁡(Q(U)≤y)=Pr⁡(U≤F(y)),=F(y).\begin{aligned} \Pr(Q(U)\le y)&=\Pr(U\le F(y)),\\ &=F(y). \end{aligned}

So Q(U)Q(U) has the desired distribution, including when FF jumps. The quantile definition and its ordering property handle the cases where an ordinary inverse does not exist.

Solving our squared-uniform CDF on its two pieces gives

Q(u)={9u2,0<u≤2/3,(6u−2)2,2/3<u<1.Q(u)= \begin{cases} 9u^2,&0<u\le2/3,\\ (6u-2)^2,&2/3<u<1. \end{cases}

For the five fixed levels 1/6,1/3,1/2,2/3,5/61/6,1/3,1/2,2/3,5/6, the outputs are 1/4,1,9/4,4,91/4,1,9/4,4,9. These are deterministic quantile checks, not a random sample.

Figure

From a probability level to the squared input

Quantile function of the squareThe curve rises from zero to sixteen. Markers show levels 1/6, 1/3, 1/2, 2/3 and 5/6, with their values in the table.0491600.51Q(u)u
Fixed check levels
uQ(u)
1/60.25
1/31
1/22.25
2/34
5/69
Five fixed levels check both pieces of the quantile function. These are not random samples. The change of slope at u = 2/3 corresponds to the end of the negative branch of the original transformation.

The reverse operation is the probability integral transform. If FXF_X is continuous, FX(X)F_X(X) is uniform on (0,1)(0,1). For a strictly increasing CDF, substitute its inverse into the event FX(X)≤uF_X(X)\le u. Continuous flat portions do not change the result because they carry zero mass. The continuity condition matters: if Pr⁡(X=0)=0.6\Pr(X=0)=0.6 and Pr⁡(X=1)=0.4\Pr(X=1)=0.4, then FX(X)F_X(X) takes only the values 0.60.6 and 11, so it cannot be uniform. See the continuous converse under Simulations.

Normalizing flows in one dimension#

An invertible transformation can also reshape a base density while keeping its value computable. Take Z∼N(0,1)Z\sim\mathcal N(0,1) and choose

g(z)=z+z33,g′(z)=1+z2.\begin{aligned} g(z)&=z+\frac{z^3}{3},\\ g'(z)&=1+z^2. \end{aligned}

The derivative is positive everywhere, and the limits at the two ends are infinite with opposite signs. Hence gg is a bijection of the real line. Writing ϕ\phi for the standard normal density, the density of Y=g(Z)Y=g(Z) obeys

fY(g(z))=ϕ(z)1+z2.f_Y(g(z))=\frac{\phi(z)}{1+z^2}.

At z=1z=1, the output is 4/34/3, its density is approximately 0.1209850.120985, and its log density is

log⁡fY(4/3)=−12−12log⁡(2π)−log⁡2,≈−2.112086.\begin{aligned} \log f_Y(4/3)&=-\frac12-\frac12\log(2\pi)-\log2,\\ &\approx-2.112086. \end{aligned}

The local stretch by 22 explains the density reduction at that point. To evaluate the density at an arbitrary supplied output, we must first solve for its input; a computable forward map alone does not remove this inversion cost.

Now append h(y)=2y−1h(y)=2y-1. The derivatives multiply under composition, so the log-density corrections add:

log⁡fh(Y)(h(g(z)))=log⁡ϕ(z)−log⁡(1+z2)−log⁡2.\log f_{h(Y)}(h(g(z)))=\log\phi(z)-\log(1+z^2)-\log2.

This is the scalar mechanism behind a normalizing flow. Rezende and Mohamed’s Section 3.1, equations (5)–(7) state the general composition rule with Jacobian determinants. The polynomial and all values here are separately constructed scalar examples; no trained model is involved.

What changed#

We can now obtain a new distribution from a known one by tracking events through a function. The same squared-uniform example supports three independent calculations: interval lengths give its CDF, branch derivatives give its density, and solving the CDF gives a sampler. Agreement between these routes is a useful check on missing branches or an incorrect support.

Limitations#

A continuous input can produce a distribution with an atom. For the same uniform input, set C=max⁡(0,X)C=\max(0,X). The entire interval [−2,0][-2,0] collapses to zero, giving Pr⁡(C=0)=1/3\Pr(C=0)=1/3. The remaining density is 1/61/6 on (0,4)(0,4) and has total mass 2/32/3. A density-only answer would miss the atom.

More generally, a derivative formula needs appropriate smooth, invertible branches and a treatment of critical points. The CDF/event method remains available when those conditions fail. Numerically, quantiles can be sensitive near tail probabilities, and pseudo-random generators have finite precision. Endpoints must be handled explicitly in code when a quantile tends to infinity. None of the finite grids shown here establishes a numerical guarantee for all distributions.

What you should remember#

Start with the output event and find its input preimage. Add masses for discrete inputs; for smooth branches, account for the change in interval length and add every valid branch. Check support and total mass before using the result. An inverse CDF turns a uniform draw into the required law, while an invertible flow preserves a tractable density through derivative corrections.

Code#

This standard-library fragment checks the quantile values and the flow density without sampling:

import math


def quantile(u):
    return 9 * u * u if u <= 2 / 3 else (6 * u - 2) ** 2


levels = [1 / 6, 1 / 3, 1 / 2, 2 / 3, 5 / 6]
print("quantiles:", " ".join(f"{quantile(u):.6f}" for u in levels))
log_density = -0.5 - 0.5 * math.log(2 * math.pi) - math.log(2)
print(f"flow at z=1: density={math.exp(log_density):.6f} log_density={log_density:.6f}")
quantiles: 0.250000 1.000000 2.250000 4.000000 9.000000
flow at z=1: density=0.120985 log_density=-2.112086

The repository’s scripts/notes/transformation-gaussian-cases.py also checks CDFs against preimage lengths, inverse identities and finite-difference derivatives, and regenerates the original figure coordinates. Its calculations are deterministic.

Next#

The distribution of a transformed variable contains more detail than many questions need. Expectation and variance develops summaries such as the mean squared error and explains how to compute them directly from the input law. For the higher-dimensional density transformation, continue later to normalizing flows.

References#