TExcelTAD
Home › Calculus in Depth › Probability

Probability

A continuous random quantity (a waiting time, a measurement error, a neuron's weight at initialisation) is described by a probability density, and every question about it becomes an integral. This lesson defines densities, the cumulative distribution function, expected value and variance, studies the exponential and normal distributions, and shows why the normal distribution sits under so much of machine learning.

Probability density functions

A continuous random variable XX has a probability density function (pdf) ff when

P(a≤X≤b)=∫abf(x) dxfor all a≤b,wheref(x)≥0and∫−∞∞f(x) dx=1P(a \le X \le b) = \int_a^b f(x)\,dx \quad \text{for all } a \le b, \quad \text{where} \quad f(x) \ge 0 \quad \text{and} \quad \int_{-\infty}^{\infty} f(x)\,dx = 1

Two consequences surprise people. First, P(X=a)=∫aaf=0P(X = a) = \int_a^a f = 0 for every single value, so ≤\le and << give the same probabilities. Second, f(x)f(x) is not a probability and can exceed 1: it is probability per unit length, so P(x≤X≤x+Δx)≈f(x) ΔxP(x \le X \le x + \Delta x) \approx f(x)\,\Delta x.

The cumulative distribution function is F(x)=P(X≤x)=∫−∞xf(t) dtF(x) = P(X \le x) = \int_{-\infty}^{x} f(t)\,dt. By the Fundamental Theorem of Calculus, F′(x)=f(x)F'(x) = f(x) wherever ff is continuous, and P(a≤X≤b)=F(b)−F(a)P(a \le X \le b) = F(b) - F(a).

Mean, variance and median

The expected value (mean) weights each value by its density, the continuous analogue of ∑xipi\sum x_i p_i:

μ=E[X]=∫−∞∞xf(x) dxσ2=Var⁡X=∫−∞∞(x−μ)2f(x) dx=E[X2]−μ2\begin{aligned} \mu &= E[X] = \int_{-\infty}^{\infty} x f(x)\,dx \\ \sigma^2 &= \operatorname{Var} X = \int_{-\infty}^{\infty} (x - \mu)^2 f(x)\,dx = E[X^2] - \mu^2 \end{aligned}

μ\mu is the balance point of the region under ff, exactly the xˉ\bar{x} of a lamina in Applications to Physics and Engineering (with total "area" 1). The median mm solves F(m)=1/2F(m) = 1/2. These integrals are improper, and they can diverge: the Cauchy density 1π(1+x2)\frac{1}{\pi(1 + x^2)} is a valid pdf with no mean at all (Exercise 3).

python · try it yourself
import sympy as sp

x, c = sp.symbols("x c", real=True)
f = c * x * (3 - x)                                   # on [0, 3], zero elsewhere

c_val = sp.solve(sp.integrate(f, (x, 0, 3)) - 1, c)[0]
f = f.subs(c, c_val)
mu = sp.integrate(x * f, (x, 0, 3))
var = sp.integrate(x**2 * f, (x, 0, 3)) - mu**2
print("c =", c_val)
print("P(X ≤ 1) =", sp.integrate(f, (x, 0, 1)))
print("mean =", mu, " variance =", var)
c = 2/9
P(X ≤ 1) = 7/27
mean = 3/2  variance = 9/20

The exponential distribution

Waiting times between independent random events (requests hitting a server, radioactive decays) are modelled by

f(t)=λe−λt for t≥0,F(t)=1−e−λt,μ=1λ,median=ln⁡2λf(t) = \lambda e^{-\lambda t} \text{ for } t \ge 0, \qquad F(t) = 1 - e^{-\lambda t}, \qquad \mu = \frac{1}{\lambda}, \qquad \text{median} = \frac{\ln 2}{\lambda}

The mean follows by parts: ∫0∞tλe−λt dt=[−te−λt]0∞+∫0∞e−λt dt=1/λ\int_0^{\infty} t \lambda e^{-\lambda t}\,dt = \left[-t e^{-\lambda t}\right]_0^{\infty} + \int_0^{\infty} e^{-\lambda t}\,dt = 1/\lambda. It is the only continuous memoryless distribution: P(T>s+t∣T>s)=e−λ(s+t)/e−λs=P(T>t)P(T > s + t \mid T > s) = e^{-\lambda(s+t)}/e^{-\lambda s} = P(T > t). Having waited 5 minutes tells you nothing about the remaining wait.

Inverse transform sampling. If UU is uniform on (0,1)(0, 1) and FF is a continuous increasing CDF, then X=F−1(U)X = F^{-1}(U) has CDF FF, because P(F−1(U)≤x)=P(U≤F(x))=F(x)P(F^{-1}(U) \le x) = P(U \le F(x)) = F(x). For the exponential, X=−ln⁡(1−U)/λX = -\ln(1 - U)/\lambda. This is how random-number libraries turn uniform bits into other distributions.

python · try it yourself
import numpy as np

rng = np.random.default_rng(11)
lam = 0.5                                   # one event every 2 s on average
U = rng.random(100_000)
T = -np.log(1 - U) / lam                    # inverse transform

print(f"sample mean {float(T.mean()):.3f}   theory 1/λ = {1 / lam:.3f}")
print(f"P(T > 3)    {float(np.mean(T > 3)):.4f}  theory e^(-1.5) = {np.exp(-1.5):.4f}")
waited = T[T > 2] - 2                       # memoryless: remaining wait after 2 s
print(f"mean remaining wait after 2 s: {float(waited.mean()):.3f}")
sample mean 2.001   theory 1/λ = 2.000
P(T > 3)    0.2227  theory e^(-1.5) = 0.2231
mean remaining wait after 2 s: 1.995

The normal distribution

The normal (Gaussian) density with mean μ\mu and standard deviation σ\sigma is

f(x)=1σ2π⋅e−(x−μ)2/(2σ2)f(x) = \frac{1}{\sigma\sqrt{2\pi}} \cdot e^{-(x - \mu)^2/(2\sigma^2)}

Its antiderivative is not elementary, so the constant 1σ2π\frac{1}{\sigma\sqrt{2\pi}} comes from the Gaussian integral ∫−∞∞e−x2 dx=π\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}, proved by squaring it and switching to polar coordinates (Double Integrals in Polar Coordinates). Probabilities are computed with the error function erf⁡\operatorname{erf}, which libraries implement with series and rational approximations (Applications of Taylor Polynomials). The central limit theorem explains its ubiquity: sums of many small independent effects are approximately normal (Central Limit Theorem).

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from math import erf, sqrt
from scipy.integrate import quad

pdf = lambda x: np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
total, _ = quad(pdf, -np.inf, np.inf)
print(f"∫ pdf = {total:.10f}")
for k in (1, 2, 3):
    print(f"P(|Z| < {k}) = {erf(k / sqrt(2)):.4f}")

xs = np.linspace(-4, 4, 400)
plt.figure(figsize=(6, 3.5))
plt.plot(xs, pdf(xs), color="C0")
band = (xs > -1) & (xs < 1)
plt.fill_between(xs[band], pdf(xs[band]), alpha=0.3, label="P(|Z| < 1) ≈ 0.683")
plt.title("Standard normal density"); plt.legend(); plt.grid(alpha=0.3)
print("plotted the standard normal pdf with the ±1σ area shaded")
∫ pdf = 1.0000000000
P(|Z| < 1) = 0.6827
P(|Z| < 2) = 0.9545
P(|Z| < 3) = 0.9973
plotted the standard normal pdf with the ±1σ area shaded

In software: the normal distribution in ML

  • Mean squared error is a Gaussian likelihood. If a model predicts y^i\hat{y}_i and the noise is normal with fixed σ\sigma, the negative log-likelihood of the data is ∑(yi−y^i)2/(2σ2)+nln⁡(σ2π)\sum (y_i - \hat{y}_i)^2/(2\sigma^2) + n \ln(\sigma\sqrt{2\pi}). Minimising it is minimising the squared error, which is why linear regression uses MSE (Linear Regression).
  • Weight initialisation. Neural networks draw initial weights from N(0,σ2)N(0, \sigma^2) with σ2=2/nin\sigma^2 = 2/n_{\text{in}} (He) or 1/nin1/n_{\text{in}} (Xavier) so that the variance of activations, an integral like E[X2]E[X^2], stays stable from layer to layer.
  • Sampling and noise. Diffusion models add and remove Gaussian noise; VAEs sample z=μ+σ⋅εz = \mu + \sigma \cdot \varepsilon with ε∼N(0,1)\varepsilon \sim N(0, 1); Gaussian naive Bayes and anomaly detectors evaluate normal densities. See Probability Densities in AI for more, and the survey treatment in Normal Distribution.

Exercises

Exercise 1: Normalise a density

Find kk so that f(x)=kx2f(x) = k x^2 on [0,2][0, 2] is a pdf, then compute P(X>1)P(X > 1) and E[X]E[X].

Answer

k=3/8k = 3/8, P(X>1)=7/8P(X > 1) = 7/8, E[X]=3/2E[X] = 3/2.

Solution
∫02kx2 dx=8k3=1⇒k=38P(X>1)=38∫12x2 dx=38⋅73=78E[X]=38∫02x3 dx=38⋅4=32\begin{aligned} \int_0^2 kx^2\,dx &= \frac{8k}{3} = 1 && \Rightarrow \quad k = \frac{3}{8} \\ P(X > 1) &= \frac{3}{8} \int_1^2 x^2\,dx = \frac{3}{8} \cdot \frac{7}{3} = \frac{7}{8} \\ E[X] &= \frac{3}{8} \int_0^2 x^3\,dx = \frac{3}{8} \cdot 4 = \frac{3}{2} \end{aligned}

Exercise 2: Median of the exponential

Show that the median of the exponential distribution is ln⁡2/λ\ln 2/\lambda. For a server with a mean gap of 2 s between requests, what is the median gap?

Answer

m=ln⁡2/λm = \ln 2/\lambda; with λ=0.5\lambda = 0.5, m≈1.386 sm \approx 1.386\ \text{s}.

Solution
F(m)=1−e−λm=12⇒e−λm=12⇒m=ln⁡2λλ=12⇒m=2ln⁡2≈1.386 s(less than the mean: the density is skewed right)\begin{aligned} &F(m) = 1 - e^{-\lambda m} = \tfrac{1}{2} \quad \Rightarrow \quad e^{-\lambda m} = \tfrac{1}{2} \quad \Rightarrow \quad m = \frac{\ln 2}{\lambda} \\ &\lambda = \tfrac{1}{2} \quad \Rightarrow \quad m = 2 \ln 2 \approx 1.386\ \text{s} && \text{(less than the mean: the density is skewed right)} \end{aligned}

Exercise 3: A density without a mean

Show that f(x)=1π(1+x2)f(x) = \frac{1}{\pi(1 + x^2)} is a pdf, and that ∫0∞xf(x) dx\int_0^{\infty} x f(x)\,dx diverges.

Answer

∫f=1\int f = 1, but ∫0Nxf dx=ln⁡(1+N2)/(2π)→∞\int_0^N x f\,dx = \ln(1 + N^2)/(2\pi) \to \infty, so the mean does not exist.

Solution
∫−∞∞dxπ(1+x2)=1π[arctan⁡x]−∞∞=1π(π2+π2)=1∫0Nxπ(1+x2) dx=ln⁡(1+N2)2π→∞\begin{aligned} \int_{-\infty}^{\infty} \frac{dx}{\pi(1 + x^2)} &= \frac{1}{\pi}\left[\arctan x\right]_{-\infty}^{\infty} = \frac{1}{\pi}\left(\frac{\pi}{2} + \frac{\pi}{2}\right) = 1 \\ \int_0^N \frac{x}{\pi(1 + x^2)}\,dx &= \frac{\ln(1 + N^2)}{2\pi} \to \infty \end{aligned}
python · try it yourself
import sympy as sp

x, N = sp.symbols("x N", positive=True)
f = 1 / (sp.pi * (1 + x**2))
print(sp.integrate(f, (x, -sp.oo, sp.oo)), "|", sp.integrate(x * f, (x, 0, N)))
1 | log(N**2 + 1)/(2*pi)

Exercise 4: Inverse transform sampling

Derive a sampler for f(x)=2xf(x) = 2x on [0,1][0, 1] and check its mean (2/32/3) on 100 000 samples.

Answer

F(x)=x2F(x) = x^2, so X=UX = \sqrt{U}; the sample mean is ≈0.667\approx 0.667.

Solution

F(x)=∫0x2t dt=x2F(x) = \int_0^x 2t\,dt = x^2, so F−1(u)=uF^{-1}(u) = \sqrt{u}. Theory: E[X]=∫012x2 dx=2/3E[X] = \int_0^1 2x^2\,dx = 2/3.

python · try it yourself
import numpy as np

rng = np.random.default_rng(5)
X = np.sqrt(rng.random(100_000))
print(f"{float(X.mean()):.4f}")
0.6671

Test yourself

A pdf has f(2)=3f(2) = 3. What does that mean?

  1. It is impossible: ff must be ≤1\le 1
  2. P(X=2)=3P(X = 2) = 3
  3. Near 2, P(2≤X≤2+Δx)≈3ΔxP(2 \le X \le 2 + \Delta x) \approx 3\Delta x
  4. P(X≤2)=3P(X \le 2) = 3

If FF is a continuous CDF, how is the pdf obtained?

  1. f=F′f = F'
  2. f=∫Ff = \int F
  3. f=1−Ff = 1 - F
  4. f=F−1f = F^{-1}

Why does least-squares regression correspond to a normal noise model?

  1. Because the normal pdf integrates to 1
  2. Because −log⁡-\log of the Gaussian likelihood is a constant plus ∑(y−y^)2/(2σ2)\sum (y - \hat{y})^2/(2\sigma^2)
  3. Because the mean equals the median
  4. It does not; it corresponds to exponential noise