Skip to main content

7  Transformations and sums

Several important distributions are easier to understand as transformations of familiar random variables than as entirely new objects. An energy measurement may be the square of a voltage; a lifetime may be the sum of two waiting times; a proportion may be a ratio of positively valued quantities. In this chapter we derive the distributions of these quantities, paying close attention to their support.

7.1 Transformations using the CDF

Let \(Y=g(X)\). By definition,

\[ F_Y(y)=P(g(X)\le y)=\int_{\{x:g(x)\le y\}}f_X(x)\,dx. \]

The integration region is the preimage of \((-\infty,y]\) under \(g\). Once the CDF is found, differentiating gives the density wherever the derivative exists.

Draw the graph of \(g\) and mark the horizontal line of height \(y\). The portion of the graph below the line tells you exactly which original \(x\) values contribute to the CDF.

7.1.1 Example: squaring a normal variable

Let \(Z\sim N(0,1)\) and \(Y=Z^2\). It is tempting to take the inverse \(Z=\sqrt Y\), but that would discard negative values of \(Z\). For \(y\ge0\),

\[ \begin{aligned} F_Y(y) &=P(-\sqrt y\le Z\le\sqrt y)\\ &=\Phi(\sqrt y)-\Phi(-\sqrt y)\\ &=2\Phi(\sqrt y)-1. \end{aligned} \]

For \(y<0\), \(F_Y(y)=0\). For \(y>0\),

\[ f_Y(y)=2\phi(\sqrt y)\frac{1}{2\sqrt y} =\frac{y^{-1/2}e^{-y/2}}{\sqrt{2\pi}}. \]

This is the chi-square density with one degree of freedom, equivalently \(\operatorname{Gamma}(1/2,1/2)\) in our shape-rate convention. Its divergence as \(y\downarrow0\) is integrable: a density can exceed one or even be unbounded.

Two shaded intervals on a standard normal density map to one shaded interval on the right-skewed chi-square density.
Figure 7.1: A nonlinear transformation can radically change the shape of a distribution. The squared normal receives probability from both signs of the original variable.

7.2 The one-dimensional change-of-variable rule

Suppose \(g\) is strictly monotone and differentiable on an interval containing the support, with differentiable inverse \(h=g^{-1}\) and nonzero derivative in the interior. Then

\[ \boxed{f_Y(y)=f_X(h(y))|h'(y)|}, \]

for \(y\) in the transformed support, and zero outside it.

Proof. If \(g\) is increasing, \(F_Y(y)=F_X(h(y))\). Differentiate by the chain rule. If \(g\) is decreasing and \(X\) is continuous, \(F_Y(y)=1-F_X(h(y))\). Differentiating now produces \(-f_X(h(y))h'(y)\). Since \(h'<0\), both cases yield the absolute derivative. \(\square\)

If \(g\) is piecewise monotone, split its domain into branches and add the density contributions:

\[ f_Y(y)=\sum_{x:g(x)=y}\frac{f_X(x)}{|g'(x)|} \]

at regular values, assuming the sum covers all relevant branches and no positive-probability interval collapses to a point. A transformation that is constant on a set of positive probability can introduce an atom.

The derivative corrects for the stretching of intervals: a small \(dy\) corresponds to approximately \(|h'(y)|\,dy\) of original width.

7.2.1 Example: lognormal processing times

Let \(X\sim N(\mu,\sigma^2)\) describe a log processing time and \(T=e^X\) be the actual time. The inverse is \(\log t\) for \(t>0\); its derivative is \(1/t\). Therefore

\[ f_T(t)=\frac{1}{t\sigma\sqrt{2\pi}} \exp\left(-\frac{(\log t-\mu)^2}{2\sigma^2}\right). \]

The median is \(e^\mu\), since \(P(X\le\mu)=1/2\). The mean is instead \(e^{\mu+\sigma^2/2}\): completing the square inside \(E[e^X]\) shows this directly. For \(\mu=0,\sigma=0.6\), the median is one time unit and the mean is \(e^{0.18}\approx1.197\). Large right-tail observations pull the mean above the median.

7.3 The probability integral transform

For a continuous random variable with strictly increasing CDF on its support, \(U=F_X(X)\) is uniform on \((0,1)\).

For \(0<u<1\),

\[ P(U\le u)=P(X\le F_X^{-1}(u))=u. \]

Conversely, for any CDF \(F\), define the generalized quantile function \(Q(u)=\inf\{x:F(x)\ge u\}\). If \(U\sim\operatorname{Uniform}(0,1)\), then \(Q(U)\) has CDF \(F\): by monotonicity and right-continuity, \(Q(u)\le x\) precisely when \(u\le F(x)\).

For an exponential distribution with rate \(\lambda\),

\[ u=1-e^{-\lambda x} \quad\Longrightarrow\quad x=-\frac{\log(1-u)}{\lambda}. \]

This gives a simulation algorithm starting from uniform random numbers. Its correctness is an immediate consequence of the transform theorem, not an approximation caused by a dense histogram.

7.4 Convolution: the distribution of a sum

Let \(X,Y\) be independent continuous variables with densities \(f_X,f_Y\). Set \(S=X+Y\). Conditioning on \(X=x\) gives

\[ F_S(s)=\int_{-\infty}^{\infty} F_Y(s-x)f_X(x)\,dx. \]

Equivalently, integrate the joint density over \(x+y\le s\) and substitute \(s'=x+y\) in the inner integral. Tonelli’s theorem (nonnegative integrands) permits exchange of integrals, yielding

\[ F_S(s)=\int_{-\infty}^s \left[\int_{-\infty}^{\infty}f_X(x)f_Y(s'-x)\,dx\right]ds'. \]

Thus the density is the convolution

\[ (f_X*f_Y)(s)=\int_{-\infty}^{\infty}f_X(x)f_Y(s-x)\,dx. \]

For integer-valued variables the corresponding PMF is

\[ P(S=k)=\sum_j p_X(j)p_Y(k-j). \]

Independence matters: without it, the integrand in the continuous formula is the joint density \(f_{X,Y}(x,s-x)\), not the product of the marginals.

7.4.1 Example: two uniform setup delays

Let \(X,Y\) be independent uniform \((0,1)\) delays. Both \(0<x<1\) and \(0<s-x<1\) are required. Their intersection gives

\[ \max(0,s-1)<x<\min(1,s). \]

The integrand equals one throughout the intersection, so its integral is just the interval length:

\[ f_S(s)= \begin{cases} s,&0<s\le1,\\ 2-s,&1<s<2,\\ 0,&\text{otherwise}. \end{cases} \]

This triangular density is symmetric about one. Its CDF on \([0,1]\) is \(s^2/2\), which gives \(P(S<0.6)=0.18\). The expected sum is one and its variance is \(1/6\), using independence.

7.5 Multivariate change of variables

Let \((U,V)=g(X,Y)\) be a one-to-one differentiable map on the support with differentiable inverse \((x(u,v),y(u,v))\). If the inverse Jacobian determinant is nonzero in the interior, the transformed density is

\[ f_{U,V}(u,v) =f_{X,Y}(x(u,v),y(u,v)) \left|\det\begin{pmatrix} \partial x/\partial u & \partial x/\partial v\\ \partial y/\partial u & \partial y/\partial v \end{pmatrix}\right|. \]

The change-of-variables theorem for integration proves this formula: integrate \(f_{X,Y}\) over the inverse image of any measurable region in the new coordinates. Locally the inverse map is approximately linear, so the determinant measures how much it expands infinitesimal area. The absolute value discards orientation while preserving area.

7.5.1 Example: the total and share of two waiting times

Suppose \(X,Y\) are independent exponential variables of equal rate \(\lambda\). Set

\[ T=X+Y,\qquad R=\frac{X}{X+Y}. \]

Their original joint density is \(\lambda^2 e^{-\lambda(x+y)}\) for \(x,y>0\). The inverse is \(x=tr\), \(y=t(1-r)\), with \(t>0\) and \(0<r<1\). Its determinant is

\[ \det\begin{pmatrix}r&t\\1-r&-t\end{pmatrix}=-t. \]

Consequently,

\[ f_{T,R}(t,r)=\lambda^2te^{-\lambda t}\, \mathbf1_{\{t>0\}}\mathbf1_{\{0<r<1\}}. \]

This factors into a \(\operatorname{Gamma}(2,\lambda)\) density and a uniform density on \((0,1)\). Therefore the total waiting time and proportion spent in the first stage are independent. Their independence is a result of equal rates and exponential structure, not a generic property of totals and shares.

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

rng = np.random.default_rng(807)
rate, n = 2.0, 40_000
x, y = rng.exponential(1/rate, size=(2, n))
t, r = x+y, x/(x+y)
print("Means (theory: 1 and 0.5):", t.mean(), r.mean())
print("Correlation:", np.corrcoef(t, r)[0, 1])
grid = np.linspace(0, 4, 250)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.3))
axes[0].hist(t, bins=55, density=True, alpha=.5)
axes[0].plot(grid, stats.gamma.pdf(grid, a=2, scale=1/rate))
axes[0].set(xlabel="Total", ylabel="Density")
axes[1].scatter(t[:1200], r[:1200], s=7, alpha=.3)
axes[1].set(xlabel="Total", ylabel="First-stage share", ylim=(0, 1))
plt.tight_layout()
plt.show()

The sample correlation is near zero, consistent with our proof. The scatterplot is a useful diagnostic, but the analytic density factorization is what establishes independence.

7.6 Order statistics

Let \(X_1,\ldots,X_n\) be iid with continuous CDF \(F\) and density \(f\). Denote their sorted values by \(X_{(1)}\le\cdots\le X_{(n)}\).

The maximum has CDF \(F_{X_{(n)}}(x)=F(x)^n\), because every observation must be at most \(x\). The minimum has CDF \(1-[1-F(x)]^n\), because its complement requires every observation to exceed \(x\).

For the \(k\)th smallest observation, there must be at least \(k\) observations at or below \(x\). The number of those observations is binomial, so

\[ P(X_{(k)}\le x)=\sum_{j=k}^n\binom nj F(x)^j[1-F(x)]^{n-j}. \]

Differentiating the sum with respect to \(F(x)\) causes consecutive terms to cancel, using \(j\binom nj=n\binom{n-1}{j-1}\) and \((n-j)\binom nj=n\binom{n-1}{j}\). The remaining term yields

\[ f_{X_{(k)}}(x)=\frac{n!}{(k-1)!(n-k)!}F(x)^{k-1}[1-F(x)]^{n-k}f(x). \]

In particular, uniform order statistics are beta variables. For a sample of five uniform observations, the median has \(\operatorname{Beta}(3,3)\) density.

7.7 Practice problems

Work in your browser with Google Colab, or download the notebooks for Jupyter.

Practice notebook

Open in Colab Download .ipynb

Worked solutions

Open in Colab Download .ipynb

7.7.1 Exercise 1: A decreasing transformation

For \(X\sim\operatorname{Uniform}(1,3)\), derive the density, support, and expectation of \(Y=1/X\). Check that the density integrates to one.

The inverse is \(x=1/y\). On \(1/3<y<1\), \[ f_Y(y)=\frac{1}{2y^2}. \] Its integral equals \([-1/(2y)]_{1/3}^1=1\). The mean is \(\int_{1/3}^1 y/(2y^2)\,dy=\tfrac12\log3\).

7.7.2 Exercise 2: Difference of uniform measurements

Let \(X,Y\) be independent uniform \((0,1)\). Find the density of \(D=X-Y\) and evaluate \(P(|D|\le0.2)\).

Use \(f_D(d)=\int f_X(x)f_Y(x-d)\,dx\). The permitted interval for \(x\) is \((0,1)\cap(d,d+1)\), whose length is \(1-|d|\) for \(|d|<1\), and zero otherwise. Therefore \[ P(|D|\le0.2)=2\int_0^{0.2}(1-d)\,dd=0.36. \]

7.7.3 Exercise 3: A two-dimensional map

For independent standard normal variables \(X,Y\), derive the joint density of \(U=X+Y\) and \(V=X-Y\). Are \(U\) and \(V\) independent?

The inverse is \(x=(u+v)/2\), \(y=(u-v)/2\); the determinant of its Jacobian is \(-1/2\). Since \(x^2+y^2=(u^2+v^2)/2\), \[ f_{U,V}(u,v)=\frac{1}{4\pi}e^{-u^2/4}e^{-v^2/4}. \] Each factor, normalized by \(1/\sqrt{4\pi}\), is a \(N(0,2)\) density. Thus the transformed variables are independent.

7.7.4 Exercise 4: Build an inverse-CDF sampler in Python

Using only uniform random numbers, generate 50,000 samples from \(\operatorname{Exponential}(3)\). Compare the sample mean, 90th percentile, and histogram to the exact values. Why use the log1p function?

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

rng = np.random.default_rng(701)
u = rng.random(50_000)
x = -np.log1p(-u)/3
print("Mean:", x.mean(), 1/3)
print("90th percentile:", np.quantile(x, .9), np.log(10)/3)
g = np.linspace(0, 2.5, 300)
plt.hist(x, bins=60, density=True, alpha=.5)
plt.plot(g, stats.expon.pdf(g, scale=1/3))
plt.xlabel("Simulated waiting time")
plt.ylabel("Density")
plt.show()
assert abs(x.mean()-1/3) < .01

The function log1p(-u) computes \(\log(1-u)\) accurately near zero, avoiding unnecessary rounding from first subtracting a tiny \(u\) from one.

7.7.5 Exercise 5: Predict a convolution before simulating it (Python)

From 80,000 independent pairs of uniform samples, estimate the probability their sum is at most 0.6. Plot the empirical density and triangle from the derivation. Estimate the simulation standard error.

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(702)
n = 80_000
s = rng.random((n, 2)).sum(axis=1)
p = np.mean(s <= .6)
se = np.sqrt(p*(1-p)/n)
print(f"Estimate {p:.5f}, theory .18, Monte Carlo SE {se:.5f}")
g = np.linspace(0, 2, 301)
plt.hist(s, bins=60, density=True, alpha=.5)
plt.plot(g, 1-np.abs(g-1))
plt.xlabel("Sum")
plt.ylabel("Density")
plt.show()
assert abs(p-.18) < 5*se

The indicator average is a proportion of independent successes. Its variance is \(p(1-p)/n\), so the empirical discrepancy should typically be a few standard errors at most.

7.7.6 Exercise 6: Simulate the median (Python)

Generate 40,000 samples of size five from a uniform distribution. Compare the histogram of their medians to the \(\operatorname{Beta}(3,3)\) density. Verify its mean and variance.

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt

rng = np.random.default_rng(703)
m = np.median(rng.random((40_000, 5)), axis=1)
g = np.linspace(0, 1, 200)
print(m.mean(), .5)
print(m.var(), 3*3/(6**2*7))
plt.hist(m, bins=45, density=True, alpha=.55)
plt.plot(g, stats.beta.pdf(g, 3, 3))
plt.xlabel("Sample median")
plt.ylabel("Density")
plt.show()
assert abs(m.var()-1/28) < .002

The theoretical mean is \(3/(3+3)=1/2\) and the variance is \(9/(36\cdot7)=1/28\).