Skip to content
VibeFormer
Advanced26 min

Transformations of Random Variables

The CDF method, change-of-variables with Jacobians, and inverse transform sampling.

Assumes you know

Transformations of Random Variables

Intuition first

You know the distribution of XX and you need the distribution of g(X)g(X) — a squared value, a logarithm, a reciprocal. This comes up constantly: log-transforming skewed data, converting between units, deriving the chi-squared from the normal, simulating any distribution from a uniform.

There are two reliable methods.

The CDF method always works: write P(Yy)\Prob(Y \leq y), rearrange the inequality in terms of XX, then read off or differentiate. Slower, but it never lies to you about monotonicity or about multiple branches.

The change-of-variables formula is faster but only applies when gg is monotone. Its essential ingredient is the dx/dy\lvert dx/dy \rvert factor, which accounts for the transformation stretching or compressing the axis. Forgetting it is the single most common error, and it produces a "density" that does not integrate to 1.

The CDF method

Three steps, in order:

  1. Write FY(y)=P(Yy)=P(g(X)y)F_Y(y) = \Prob(Y \leq y) = \Prob(g(X) \leq y).
  2. Rearrange the inequality into a statement about XX.
  3. Express in terms of FXF_X, then differentiate for the density.

Solved problem 1 · The square of a uniform

XUniform(0,1)X \sim \text{Uniform}(0,1) and Y=X2Y = X^2. Find the density of YY.

Step 1 — the support

X(0,1)X \in (0,1) so Y=X2(0,1)Y = X^2 \in (0,1) as well.

Step 2 — write the CDF and rearrange

FY(y)=P(X2y)F_Y(y) = \Prob(X^2 \leq y)

Since X>0X > 0 on the support, taking square roots preserves the inequality:

=P(Xy)=FX(y)= \Prob(X \leq \sqrt{y}) = F_X(\sqrt{y})

Step 3 — substitute the uniform CDF

For Uniform(0,1)\text{Uniform}(0,1), FX(x)=xF_X(x) = x, so

FY(y)=y,0<y<1F_Y(y) = \sqrt{y}, \qquad 0 < y < 1

Step 4 — differentiate

fY(y)=ddyy1/2=12y,0<y<1f_Y(y) = \frac{d}{dy}\,y^{1/2} = \frac{1}{2\sqrt{y}}, \qquad 0 < y < 1

Step 5 — verify it is a density

0112ydy=[y]01=1  \int_0^1 \frac{1}{2\sqrt{y}}\,dy = \left[\sqrt{y}\right]_0^1 = 1 \;\checkmark

Step 6 — interpret

The density blows up as y0y \to 0, since 1/(2y)1/(2\sqrt{y}) \to \infty, yet the integral is finite. This is the squaring compressing the interval near zero: values of XX in (0,0.1)(0, 0.1) — 10% of the probability — get squeezed into Y(0,0.01)Y \in (0, 0.01), just 1% of the range, so the density there must be about ten times larger.

Note also that fYf_Y exceeds 1 on part of its range, which is allowed: densities are not probabilities.

Answer

fY(y)=12yf_Y(y) = \dfrac{1}{2\sqrt{y}} for 0<y<10 < y < 1. This is Beta(12,1)\text{Beta}(\tfrac12, 1).

The change-of-variables formula

If gg is monotone and differentiable with inverse x=g1(y)x = g^{-1}(y):

fY(y)=fX(g1(y))dxdyf_Y(y) = f_X\big(g^{-1}(y)\big)\left\lvert \frac{dx}{dy} \right\rvert
Where the Jacobian factor comes fromAdvanced

Probability must be conserved: the chance of landing in a small interval cannot change just because we relabelled the axis. For a small interval dxdx mapping to dydy:

fX(x)dx=fY(y)dyf_X(x)\,\lvert dx \rvert = f_Y(y)\,\lvert dy \rvert

Dividing:

fY(y)=fX(x)dxdyf_Y(y) = f_X(x)\left\lvert \frac{dx}{dy} \right\rvert

The absolute value is needed because a decreasing gg has negative derivative, while densities must be non-negative — and because the direction of the interval is irrelevant to its probability.

Why monotonicity is required. If gg is not monotone, several xx values map to the same yy, and probability arrives at yy from each branch. Take Y=X2Y = X^2 with XX on (1,1)(-1, 1): both x=+yx = +\sqrt y and x=yx = -\sqrt y contribute, so

fY(y)=branches ifX(gi1(y))dxidyf_Y(y) = \sum_{\text{branches } i} f_X\big(g_i^{-1}(y)\big)\left\lvert \frac{dx_i}{dy}\right\rvert

Applying the single-branch formula would miss half the probability. In Solved problem 1 the issue did not arise because X>0X > 0 made the squaring monotone on its support — worth checking every time.

Solved problem 2 · Deriving the lognormal

XN(μ,σ2)X \sim \mathcal{N}(\mu, \sigma^2) and Y=eXY = e^X. Find the density of YY, and its mean.

Step 1 — check monotonicity and support

g(x)=exg(x) = e^x is strictly increasing on all of R\mathbb{R}, so the single-branch formula applies. Its range is (0,)(0, \infty), so Y>0Y > 0.

Step 2 — invert and differentiate

y=exx=lny,dxdy=1yy = e^x \quad\Longrightarrow\quad x = \ln y, \qquad \frac{dx}{dy} = \frac{1}{y}

Since y>0y > 0, the absolute value is just 1/y1/y.

Step 3 — apply the formula

fY(y)=fX(lny)1y=1σ2πexp((lnyμ)22σ2)1yf_Y(y) = f_X(\ln y)\cdot\frac{1}{y} = \frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{(\ln y - \mu)^2}{2\sigma^2}\right)\cdot\frac{1}{y}fY(y)=1yσ2πexp((lnyμ)22σ2),y>0f_Y(y) = \frac{1}{y\sigma\sqrt{2\pi}}\exp\left(-\frac{(\ln y - \mu)^2}{2\sigma^2}\right), \qquad y > 0

This is the lognormal density.

Step 4 — the mean, using the normal MGF

E[Y]=E[eX]=MX(1)\E[Y] = \E[e^X] = M_X(1)

The normal MGF is MX(t)=exp(μt+12σ2t2)M_X(t) = \exp(\mu t + \tfrac12\sigma^2 t^2), so at t=1t = 1:

E[Y]=exp(μ+σ22)\E[Y] = \exp\left(\mu + \frac{\sigma^2}{2}\right)

Step 5 — note the trap

E[eX]=eμ+σ2/2    eE[X]=eμ\E[e^X] = e^{\mu + \sigma^2/2} \;\neq\; e^{\E[X]} = e^{\mu}

The gap is the factor eσ2/2>1e^{\sigma^2/2} > 1. This is Jensen's inequality: exe^x is convex, so E[eX]>eE[X]\E[e^X] > e^{\E[X]}.

Concretely, with μ=0\mu = 0 and σ=1\sigma = 1: the median of YY is e0=1e^0 = 1, but the mean is e0.51.649e^{0.5} \approx 1.649 — 65% higher. The lognormal is right-skewed, so its mean substantially exceeds its median.

Answer

fY(y)=1yσ2πexp ⁣((lnyμ)22σ2)f_Y(y) = \dfrac{1}{y\sigma\sqrt{2\pi}}\exp\!\left(-\dfrac{(\ln y - \mu)^2}{2\sigma^2}\right) for y>0y > 0, with E[Y]=eμ+σ2/2\E[Y] = e^{\mu + \sigma^2/2} and median eμe^{\mu}.

The standard transformations

TransformationResult
aX+baX + b, XX normalNormal: N(aμ+b,  a2σ2)\mathcal{N}(a\mu+b,\; a^2\sigma^2)
(Xμ)/σ(X - \mu)/\sigma, XX normalStandard normal
Z2Z^2, ZZ standard normalχ12\chi^2_1
i=1kZi2\sum_{i=1}^k Z_i^2χk2\chi^2_k
eXe^X, XX normalLognormal
F1(U)F^{-1}(U), UU uniformAny distribution with CDF FF
ln(U)/λ-\ln(U)/\lambda, UU uniformExponential(λ)\text{Exponential}(\lambda)
i=1αEi\sum_{i=1}^{\alpha} E_i, EiE_i exponentialGamma(α,β)\text{Gamma}(\alpha, \beta)

Solved problem 3 · Z² is chi-squared with one degree of freedom

Show that if ZN(0,1)Z \sim \mathcal{N}(0,1) then Z2χ12Z^2 \sim \chi^2_1.

Step 1 — recognise the non-monotonicity

g(z)=z2g(z) = z^2 is not monotone on R\mathbb{R}: both +y+\sqrt y and y-\sqrt y map to yy. Use the CDF method, which handles this automatically.

Step 2 — write the CDF

For y>0y > 0:

FY(y)=P(Z2y)=P(yZy)=Φ(y)Φ(y)F_Y(y) = \Prob(Z^2 \leq y) = \Prob(-\sqrt{y} \leq Z \leq \sqrt{y}) = \Phi(\sqrt{y}) - \Phi(-\sqrt{y})

By the symmetry of the standard normal, Φ(a)=1Φ(a)\Phi(-a) = 1 - \Phi(a):

FY(y)=2Φ(y)1F_Y(y) = 2\Phi(\sqrt{y}) - 1

Step 3 — differentiate

fY(y)=2ϕ(y)ddyy=2ϕ(y)12y=ϕ(y)yf_Y(y) = 2\,\phi(\sqrt{y})\cdot\frac{d}{dy}\sqrt{y} = 2\,\phi(\sqrt{y})\cdot\frac{1}{2\sqrt{y}} = \frac{\phi(\sqrt{y})}{\sqrt{y}}

Step 4 — substitute the normal density

With ϕ(z)=12πez2/2\phi(z) = \frac{1}{\sqrt{2\pi}}e^{-z^2/2} and z=yz = \sqrt y, so z2=yz^2 = y:

fY(y)=1y12πey/2=12πy1/2ey/2f_Y(y) = \frac{1}{\sqrt{y}}\cdot\frac{1}{\sqrt{2\pi}}e^{-y/2} = \frac{1}{\sqrt{2\pi}}\,y^{-1/2}e^{-y/2}

Step 5 — match against the chi-squared density

The χk2\chi^2_k density is

f(y)=12k/2Γ(k/2)yk/21ey/2f(y) = \frac{1}{2^{k/2}\Gamma(k/2)}y^{k/2 - 1}e^{-y/2}

Set k=1k = 1. Then yk/21=y1/2y^{k/2-1} = y^{-1/2} ✓, and the constant is

121/2Γ(1/2)=12π=12π  \frac{1}{2^{1/2}\Gamma(1/2)} = \frac{1}{\sqrt{2}\cdot\sqrt{\pi}} = \frac{1}{\sqrt{2\pi}} \;\checkmark

using Γ(12)=π\Gamma(\tfrac12) = \sqrt\pi. The two expressions are identical.

Answer

Z2χ12Z^2 \sim \chi^2_1. The two branches of the squaring produced the factor of 2 that, combined with Γ(12)=π\Gamma(\tfrac12) = \sqrt\pi, makes the constants match exactly.

python
import numpy as np
from scipy import stats

rng = np.random.default_rng(0)

# Y = X² for X uniform: density 1/(2√y).
U = rng.random(500_000)
Y = U ** 2
q = np.linspace(0.05, 0.95, 5)
print("quantile  empirical   theory √q")
for p in q:
    print(f"{p:8.2f}  {np.quantile(Y, p):9.4f}   {p**2:9.4f}")

# Lognormal: mean vs median, the Jensen gap.
mu, sigma = 0.0, 1.0
X = rng.normal(mu, sigma, 1_000_000)
L = np.exp(X)
print(f"\nlognormal mean   {L.mean():.4f}   theory e^(μ+σ²/2) = {np.exp(mu + sigma**2/2):.4f}")
print(f"lognormal median {np.median(L):.4f}   theory e^μ       = {np.exp(mu):.4f}")
print(f"exp(E[X])        {np.exp(X.mean()):.4f}   <- NOT the mean of Y")

# Z² is chi-squared with 1 df.
Z = rng.standard_normal(1_000_000)
print(f"\nZ²: mean {np.mean(Z**2):.4f} (theory 1)  var {np.var(Z**2):.4f} (theory 2)")
print(f"KS test against chi2(1): p = {stats.kstest(Z**2, 'chi2', args=(1,)).pvalue:.3f}")

# Inverse transform sampling for the exponential.
E = -np.log(rng.random(500_000)) / 3.0
print(f"\ninverse transform exponential(3): mean {E.mean():.4f} (theory {1/3:.4f})")

Exercise 1

XExponential(λ)X \sim \text{Exponential}(\lambda) and Y=XY = \sqrt{X}. Find the density of YY.

Show solution

g(x)=xg(x) = \sqrt x is increasing on (0,)(0,\infty), so the change-of-variables formula applies.

Invert and differentiate:

y=xx=y2,dxdy=2yy = \sqrt x \quad\Longrightarrow\quad x = y^2, \qquad \frac{dx}{dy} = 2y

Apply the formula with fX(x)=λeλxf_X(x) = \lambda e^{-\lambda x}:

fY(y)=λeλy22y=2λyeλy2,y>0f_Y(y) = \lambda e^{-\lambda y^2} \cdot 2y = 2\lambda y\, e^{-\lambda y^2}, \qquad y > 0

Check normalisation by substituting u=y2u = y^2, du=2ydydu = 2y\,dy:

02λyeλy2dy=0λeλudu=1  \int_0^\infty 2\lambda y e^{-\lambda y^2}dy = \int_0^\infty \lambda e^{-\lambda u}\,du = 1 \;\checkmark

This is a Rayleigh distribution with scale 1/2λ1/\sqrt{2\lambda}. It is the distribution of the magnitude of a two-dimensional vector with independent normal components, which is how it arises in signal processing and wind-speed modelling.

Exercise 2

Explain why a regression fitted to log(revenue)\log(\text{revenue}) under-predicts total revenue when predictions are exponentiated, and give the correction.

Show solution

A least-squares regression on logY\log Y estimates E[logYx]\E[\log Y \mid x] — the conditional mean of the log. Exponentiating gives

exp(E[logYx])\exp\big(\E[\log Y \mid x]\big)

which, by the lognormal result, is the conditional median of YY, not its mean:

E[Yx]=exp(E[logYx]+σ22)\E[Y \mid x] = \exp\left(\E[\log Y \mid x] + \frac{\sigma^2}{2}\right)

where σ2\sigma^2 is the variance of the residuals on the log scale. Since eσ2/2>1e^{\sigma^2/2} > 1, the naive back-transform is always too small.

Because revenue is right-skewed, the mean exceeds the median, and summing medians across customers systematically undershoots the total. The error compounds: with residual standard deviation σ=0.6\sigma = 0.6 on the log scale, the correction factor is

e0.36/2=e0.181.197e^{0.36/2} = e^{0.18} \approx 1.197

so totals are understated by about 20%.

The correction is to multiply predictions by eσ^2/2e^{\hat\sigma^2/2}, using the residual variance from the fitted log-scale model. A more robust alternative that does not assume lognormal residuals is Duan's smearing estimator: multiply by the mean of eε^ie^{\hat\varepsilon_i} over the residuals.

The cleanest option when you need means rather than medians is to avoid the log transform altogether and fit a generalised linear model with a log link — a gamma or Poisson GLM — which models E[Yx]\E[Y \mid x] directly and requires no back-transformation at all.


Next: Joint Continuous Distributions.