Skip to main content

4  Continuous random variables

A sensor can report any real temperature in a range, and a financial return can take values on the entire real line. Assigning a positive probability to every possible real value is impossible: a probability distribution has total mass one. We instead describe the mass of intervals using calculus.

4.1 Cumulative distribution and density

The CDF \(F_X(x)=\Pr(X\le x)\) is defined for every random variable, including variables with discrete, continuous or mixed distributions. We call a distribution absolutely continuous if for some integrable function \(f_X\),

\[ F_X(x)=\int_{-\infty}^x f_X(t)\,dt,\qquad f_X(x)\ge0,\qquad\int_{-\infty}^{\infty} f_X(t)\,dt=1. \]

The function \(f_X\) is a probability density function (PDF). By the fundamental theorem of calculus, \(f_X(x)=F_X'(x)\) at points where the density is continuous (and almost everywhere more generally). For an interval,

\[ \Pr(a<X\le b)=F_X(b)-F_X(a)=\int_a^b f_X(t)\,dt. \]

Since single points have zero length, \(\Pr(X=a)=0\) in an absolutely continuous model. This does not mean that observing a real value is impossible; observations are usually reported to finite precision, corresponding to intervals. Density is probability per unit of the variable, not probability at a point.

A PDF may exceed one. For a uniform distribution on \([0,0.2]\), the density equals five but the total area is \(5(0.2)=1\).

4.1.1 Worked example: ramp-shaped density

An idealized response time \(X\) in seconds has density

\[ f_X(x)= \begin{cases} cx,&0\le x\le2,\\ 0,&\text{otherwise}. \end{cases} \]

Normalization requires \(c\int_0^2 x\,dx=2c=1\), hence \(c=1/2\). Integrating the density to \(x\) gives

\[ F_X(x)= \begin{cases} 0,&x<0,\\ x^2/4,&0\le x\le2,\\ 1,&x>2. \end{cases} \]

The probability of responding between 1 and 1.5 seconds is \(F_X(1.5)-F_X(1)=2.25/4-1/4=0.3125\). The median is the point where \(F_X(x)=1/2\), namely \(\sqrt2\) seconds.

The triangular density x/2 on zero to two, shading the interval one to 1.5, and the quadratic cumulative distribution.

A ramp density, its cumulative distribution and the area corresponding to a time interval.

4.2 Mean, variance and quantiles

For an integrable function \(g(X)\), the continuous form of LOTUS is

\[ \operatorname{E}[g(X)]=\int_{-\infty}^\infty g(x)f_X(x)\,dx. \]

This follows first for indicator functions of intervals from the probability formula, then for simple functions by linearity, and for nonnegative or integrable functions by approximation. Existence of \(\operatorname{E}[X]\) as a finite number requires \(\int |x| f_X(x)\,dx<\infty\). If the second moment is finite,

\[ \operatorname{Var}(X)=\int x^2 f_X(x)\,dx-\left(\int xf_X(x)\,dx\right)^2. \]

For the ramp model,

\[ \operatorname{E}X=\frac12\int_0^2 x^2dx=\frac43,\qquad \operatorname{E}X^2=\frac12\int_0^2x^3dx=2, \]

so \(\operatorname{Var}(X)=2-16/9=2/9\).

The general \(p\)-quantile, \(0<p<1\), is \(q_p=\inf\{x:F_X(x)\ge p\}\). For a strictly increasing continuous CDF on its support this is simply its inverse. The first and third quartiles are \(q_{0.25}\) and \(q_{0.75}\), and their difference is the interquartile range. A median minimizes expected absolute loss \(\operatorname{E}|X-a|\) when the expectation exists; a mean minimizes expected squared loss. For squared loss, expand

\[ \operatorname{E}(X-a)^2 =\operatorname{Var}(X)+(\mu-a)^2, \]

using \(\operatorname{E}(X-\mu)=0\). The minimum occurs at \(a=\mu\). The median result follows by comparing derivatives of the expected absolute loss on either side of a continuous median: the derivative is \(2F_X(a)-1\) when the CDF is continuous.

4.3 The uniform distribution

The distribution \(U(a,b)\), \(a<b\), is specified by constant density \(1/(b-a)\) within \([a,b]\). Its CDF within that interval is \((x-a)/(b-a)\), clipped to zero or one outside. Integrating,

\[ \operatorname{E}X=\frac{a+b}{2}, \qquad \operatorname{Var}(X)=\frac{(b-a)^2}{12}. \]

One derivation of the variance uses \(X=a+(b-a)U\), where \(U\sim U(0,1)\) has moments \(\operatorname{E}U=1/2\) and \(\operatorname{E}U^2=1/3\). Hence \(\operatorname{Var}(X)=(b-a)^2(1/3-1/4)\).

Uniform random numbers are the computational starting point of many simulation methods. Later we transform them to simulate a target distribution.

4.4 Waiting times: exponential and gamma models

For a rate \(\lambda>0\), the exponential density and CDF are

\[ f(x)=\lambda e^{-\lambda x},\quad F(x)=1-e^{-\lambda x},\qquad x\ge0. \]

The survival function is \(S(x)=\Pr(X>x)=e^{-\lambda x}\). As with geometric waiting times,

\[ \Pr(X>s+t\mid X>s) =\frac{S(s+t)}{S(s)}=e^{-\lambda t}. \]

The exponential distribution is memoryless. A nonnegative waiting time with a continuous survival function, \(S(0)=1\), positive survival for finite times, vanishing as \(t\to\infty\), and the memoryless property must satisfy \(S(s+t)=S(s)S(t)\). Take \(g(t)=-\log S(t)\). Then \(g(s+t)=g(s)+g(t)\). On nonnegative rational times this implies \(g(t)=\lambda t\) with \(\lambda=g(1)\); continuity extends it to all nonnegative real times. Thus \(S(t)=e^{-\lambda t}\).

Integration by parts gives \(\operatorname{E}X=1/\lambda\) and \(\operatorname{E}X^2=2/\lambda^2\), so \(\operatorname{Var}(X)=1/\lambda^2\). More generally, \(\operatorname{E}X^r=r!/\lambda^r\) for nonnegative integer \(r\) by integration by parts repeatedly.

4.4.1 Worked example: time to service completion

If a service has an exponential completion time with mean four minutes, \(\lambda=1/4\) minute\(^{-1}\). The chance it takes more than six minutes is \(e^{-6/4}\approx0.2231\). Its 90th percentile solves \(1-e^{-x/4}=0.9\), hence \(x=4\log10\approx9.21\) minutes. The chance of waiting another six minutes after already waiting ten is again \(e^{-6/4}\) under this model. A real queue with time-varying service behavior may not be memoryless.

The gamma distribution generalizes this waiting-time model. Define

\[ \Gamma(\alpha)=\int_0^\infty t^{\alpha-1}e^{-t}\,dt,\quad\alpha>0. \]

Integration by parts yields \(\Gamma(\alpha+1)=\alpha\Gamma(\alpha)\); for positive integers \(m\), \(\Gamma(m)=(m-1)!\). The gamma density in shape-rate parametrization is

\[ f(x)=\frac{\beta^\alpha}{\Gamma(\alpha)} x^{\alpha-1}e^{-\beta x},\qquad x>0,\quad\alpha,\beta>0. \]

Substitute \(t=\beta x\) to see its integral equals one. For real \(r>-\alpha\),

\[ \operatorname{E}X^r=\frac{\Gamma(\alpha+r)} {\beta^r\Gamma(\alpha)}. \]

Thus mean \(=\alpha/\beta\) and variance \(=\alpha/\beta^2\). For integer shape \(m\) it is the law of a sum of \(m\) independent exponentials with rate \(\beta\) (derived using MGFs in Chapter 8).

The rate \(\beta\) has reciprocal units of \(X\); the scale is \(1/\beta\). SciPy’s gamma and exponential functions use the scale convention, so pass the reciprocal when your mathematical model specifies a rate.

4.5 The Gaussian or normal distribution

The standard normal density is

\[ \phi(z)=\frac1{\sqrt{2\pi}}e^{-z^2/2},\qquad -\infty<z<\infty. \]

Why the factor \(\sqrt{2\pi}\)? Let \(I=\int_{-\infty}^\infty e^{-z^2/2}dz\). The square is a double integral of a nonnegative function:

\[ \begin{aligned} I^2 &=\int_{\mathbb R^2} e^{-(x^2+y^2)/2}\,dx\,dy\\ &=\int_0^{2\pi}\int_0^\infty e^{-r^2/2}r\,dr\,d\theta\\ &=2\pi. \end{aligned} \]

The polar-coordinate Jacobian is \(r\); substitute \(u=r^2/2\) in the inner integral. Because \(I>0\), \(I=\sqrt{2\pi}\). Symmetry gives \(\operatorname{E}Z=0\). Integration by parts using \(\phi'(z)=-z\phi(z)\) gives

\[ \operatorname{E}Z^2=-\int z\phi'(z)\,dz =[-z\phi(z)]_{-\infty}^{\infty}+\int\phi(z)\,dz=1. \]

For \(X=\mu+\sigma Z\), \(\sigma>0\),

\[ X\sim N(\mu,\sigma^2),\quad f_X(x)=\frac1{\sigma}\phi\left(\frac{x-\mu}{\sigma}\right). \]

Its mean is \(\mu\), variance is \(\sigma^2\), and standardization gives \(Z=(X-\mu)/\sigma\). Write \(\Phi\) for the standard normal CDF. Then

\[ \Pr(a<X\le b)= \Phi\left(\frac{b-\mu}{\sigma}\right) -\Phi\left(\frac{a-\mu}{\sigma}\right). \]

\(\Phi\) has no elementary antiderivative; numerical evaluation is the normal approach.

4.5.1 Worked example: calibrated measurement noise

A measurement is modeled as \(N(50,2^2)\). What fraction lies outside the interval \([47,53]\)? The endpoints standardize to \(\pm1.5\), giving \(2(1-\Phi(1.5))\approx0.1336\). To leave 2% of measurements above a threshold, use \(50+2\Phi^{-1}(0.98)\approx54.11\). A distribution-based threshold controls a probability, not an absolute guarantee.

4.6 Models on bounded intervals: beta distribution

A beta random variable on \((0,1)\) has density

\[ f(x)=\frac{x^{a-1}(1-x)^{b-1}}{B(a,b)},\qquad B(a,b)=\int_0^1 x^{a-1}(1-x)^{b-1}dx, \]

for \(a,b>0\). The beta-gamma identity \(B(a,b)=\Gamma(a)\Gamma(b)/\Gamma(a+b)\) can be derived by substituting \(r=u+v\) and \(x=u/(u+v)\) in the product of the two gamma integrals; the Jacobian is \(r\). Taking ratios of normalizing constants,

\[ \operatorname{E}X=\frac{a}{a+b},\qquad \operatorname{Var}(X)=\frac{ab}{(a+b)^2(a+b+1)}. \]

The distribution is flexible: \(a=b=1\) is uniform, \(a>b\) shifts mass toward one, and \(a,b<1\) produces high density near the two endpoints. It is useful for modeling uncertain proportions in Bayesian inference.

4.7 Python experiment: compute and visualize

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

f = lambda x: x/2
normalization = integrate.quad(f, 0, 2)[0]
mu = integrate.quad(lambda x: x*f(x), 0, 2)[0]
second = integrate.quad(lambda x: x*x*f(x), 0, 2)[0]
assert np.isclose(normalization, 1)
assert np.isclose(mu, 4/3)
print("Ramp mean:", mu, "variance:", second-mu*mu)
print("Normal outside:", 2*stats.norm.sf(1.5))

rng = np.random.default_rng(404)
draws = rng.exponential(scale=4, size=20_000)
x = np.linspace(0, 22, 400)
plt.hist(draws, bins=np.linspace(0,22,45), density=False,
         weights=np.ones(draws.size)/draws.size/(22/44),
         alpha=.5, label="Simulation")
plt.plot(x, stats.expon.pdf(x, scale=4), lw=2, label="Exponential")
plt.xlabel("Minutes")
plt.ylabel("Density")
plt.legend()
plt.show()

The histogram uses a fixed normalization based on the full sample, even if a few draws exceed the displayed range. This makes the shown bars comparable to the theoretical density.

4.8 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

4.8.1 Exercise 1: A polynomial density

For \(f(x)=cx^2\) on \([0,3]\) and zero elsewhere, find \(c\), the CDF, median, mean, and variance.

The integral is \(9c\), so \(c=1/9\). For \(0\le x\le3\), \(F(x)=x^3/27\) (zero below, one above). The median is \(3\sqrt[3]{1/2}\). The mean is \(\int_0^3 x^3/9\,dx=9/4\) and the second moment is \(\int_0^3x^4/9\,dx=27/5\). The variance is \(27/5-81/16=27/80\).

4.8.2 Exercise 2: The memoryless test

A waiting time has survival function \(S(t)=e^{-t^2}\) for \(t\ge0\). Is it exponential or memoryless? Calculate the probability of waiting at least two more units given that one unit has already elapsed.

The conditional probability is \(S(3)/S(1)=e^{-9}/e^{-1}=e^{-8}\). The unconditional chance of waiting two units is \(S(2)=e^{-4}\). The unequal probabilities show the model is not memoryless and therefore not exponential. This survival function is a Weibull model with increasing hazard \(2t\).

4.8.3 Exercise 3: Gaussian specification

A dimensional tolerance requires \(\Pr(|X-10|<0.4)=0.95\) for \(X\sim N(10,\sigma^2)\). Find the maximum allowable \(\sigma\).

Standardization gives \(2\Phi(0.4/\sigma)-1=0.95\). Hence \(0.4/\sigma=\Phi^{-1}(0.975)\approx1.96\), yielding \(\sigma\approx0.20408\). Smaller \(\sigma\) increases the probability of meeting the tolerance; this is the largest allowable value.

4.8.4 Exercise 4: Python — integrate a density and invert its CDF

Use \(f(x)=6x(1-x)\) on \([0,1]\). Derive its CDF and mean. Calculate the 10th, 50th and 90th percentiles by root finding, and cross-check them with SciPy’s beta distribution.

Integrating gives \(F(x)=3x^2-2x^3\) within \([0,1]\). Symmetry about \(1/2\) gives \(\operatorname{E}X=1/2\). This is \(\operatorname{Beta}(2,2)\), because \(B(2,2)=1/6\).

from scipy.integrate import quad
from scipy.optimize import brentq
from scipy.stats import beta
import numpy as np

f = lambda x: 6*x*(1-x)
F = lambda x: 3*x*x-2*x**3
assert np.isclose(quad(f,0,1)[0],1)
print("Mean:", quad(lambda x: x*f(x),0,1)[0])
ps = np.array([.1,.5,.9])
qs = np.array([brentq(lambda x: F(x)-p,0,1) for p in ps])
print(np.c_[ps,qs])
assert np.allclose(qs,beta.ppf(ps,2,2))

4.8.5 Exercise 5: Python — calibrate a normal tail

For a process with mean 120 and standard deviation 7, find the upper threshold exceeded by 0.5% of measurements. Confirm by simulating 500,000 values. Calculate the empirical exceedance fraction and its Monte Carlo standard error.

The threshold is \(120+7\Phi^{-1}(0.995)\). Using inverse survival is a numerically convenient equivalent.

import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(410)
p, mu, sigma = .005,120,7
threshold = norm.isf(p,loc=mu,scale=sigma)
x = rng.normal(mu,sigma,500_000)
phat = (x>threshold).mean()
se = np.sqrt(p*(1-p)/x.size)
print(f"Threshold {threshold:.4f}; exceedance {phat:.6f}; SE {se:.6f}")
assert abs(phat-p)<5*se

The fraction should be close to \(0.005\), but not exactly equal. Exceeding the threshold remains possible by construction.

4.8.6 Exercise 6: Python — verify a gamma waiting-time model

Generate 80,000 independent sums of three exponential waiting times with rate \(2\). Compare their empirical mean and variance to the gamma law, and overlay a theoretical density on a histogram. Explain why a single exponential with the same mean has a different variance.

The gamma parameters are shape \(3\) and rate \(2\); the mean is \(1.5\) and variance is \(0.75\). An exponential with mean \(1.5\) has variance \(2.25\), so matching the mean does not determine the distribution.

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

rng = np.random.default_rng(411)
draws = rng.exponential(scale=.5,size=(80_000,3)).sum(axis=1)
print(draws.mean(),draws.var())
assert abs(draws.mean()-1.5)<.02
assert abs(draws.var()-.75)<.03
x = np.linspace(0,6,350)
plt.hist(draws,bins=75,density=True,alpha=.45,label="Simulated sum")
plt.plot(x,gamma.pdf(x,a=3,scale=.5),lw=2,label="Gamma(3, rate 2)")
plt.xlabel("Total waiting time")
plt.ylabel("Density")
plt.legend()
plt.show()