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 , that area follows the event back to the input:
Here means the set of preimages, even when 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:
For , the two input outcomes at each magnitude merge. They are disjoint events, so their masses add:
The general rule is a sum over all inputs with the requested output:
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 be uniform on , still with . The input interval has length , so an input event has probability equal to its length divided by .
For a nonnegative threshold , the event asks for the part of the symmetric interval that remains inside the input support:
Until , both ends move. After that, the left end is fixed at ; only the positive end continues to move. Thus
This immediately gives two checkable probabilities:
For the first, the input interval is , length . For the second, only remains in the input support; the negative interval would lie below . These event calculations check the CDF without differentiating anything.
One or two valid branches
Differentiating on the two open pieces gives a density:
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: . An infinite limiting density is not a point mass. At the density changes because one branch ends; the CDF remains continuous.
The change-of-variables formula#
Suppose has a density on an interval. If on that interval is continuously differentiable, strictly monotone and has nonzero derivative, let be its inverse. For an increasing map we have . Differentiating gives . A decreasing map reverses the event inequality and the derivative sign. Both cases give
At this is equivalently
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 and set . The range is , of length . The inverse derivative is , so 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:
Only roots inside the input support belong in the sum. For the square example, each root contributes . There are two roots below and one above . The formula applies away from the zero derivative at ; the CDF already settles what happens there.
An invertible positive transformation gives another useful distribution. Let , with , and set . Its inverse is , with derivative , so for we obtain the log-normal density:
It is zero for nonpositive . Choose and . The median is because half of the normal mass is below its mean. At that median the density is
This is a density value, not a probability of observing exactly .
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 , define the generalized quantile for by
The defining relation is exactly when . If , then
So has the desired distribution, including when 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
For the five fixed levels , the outputs are . These are deterministic quantile checks, not a random sample.
From a probability level to the squared input
| u | Q(u) |
|---|---|
| 1/6 | 0.25 |
| 1/3 | 1 |
| 1/2 | 2.25 |
| 2/3 | 4 |
| 5/6 | 9 |
The reverse operation is the probability integral transform. If is continuous, is uniform on . For a strictly increasing CDF, substitute its inverse into the event . Continuous flat portions do not change the result because they carry zero mass. The continuity condition matters: if and , then takes only the values and , 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 and choose
The derivative is positive everywhere, and the limits at the two ends are infinite with opposite signs. Hence is a bijection of the real line. Writing for the standard normal density, the density of obeys
At , the output is , its density is approximately , and its log density is
The local stretch by 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 . The derivatives multiply under composition, so the log-density corrections add:
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 . The entire interval collapses to zero, giving . The remaining density is on and has total mass . 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#
- Kyle Siegrist, Transformations of Random Variables, Basic Theory, The Change of Variables Formula, and Simulations: event preimages, smooth transformations and inverse sampling.
- Kyle Siegrist, Distribution and Quantile Functions, Quantile Functions: generalized inverse and its ordering property.
- Danilo Jimenez Rezende and Shakir Mohamed, Variational Inference with Normalizing Flows, ICML 2015; arXiv v6, 2016, Section 3.1, equations (5)–(7): invertible density transformations and composition.