TExcelTAD
Home › Probability Theory › Gamma, Beta and Chi-Squared

Gamma, Beta and Chi-Squared

A few more continuous families appear constantly in probability, statistics and machine learning. Each one has a natural story that explains where it comes from, and knowing the story is more useful than memorising the formula.

Gamma: waiting for several events

The time until the kk-th event of a Poisson process with rate λ\lambda is the sum of kk independent exponential gaps. Its density is the gamma (Erlang) density

f(t)=λktk−1(k−1)!e−λt,t≥0f(t) = \frac{\lambda^k t^{k-1}}{(k-1)!} e^{-\lambda t}, \qquad t \ge 0

with mean k/λk/\lambda and variance k/λ2k/\lambda^2. It is the continuous analogue of the negative binomial. With non-integer kk, (k−1)!(k-1)! is replaced by the gamma function Γ(k)\Gamma(k).

python · try it yourself
import random
import math

rng = random.Random(1)
lam, k, n = 2.0, 3, 100_000
T = [sum(rng.expovariate(lam) for _ in range(k)) for _ in range(n)]
print("mean:", round(sum(T) / n, 4), " k/lambda =", k / lam)

def gamma_cdf(t, k, lam):           # P(T <= t) = P(at least k events by time t)
    return 1 - sum(math.exp(-lam * t) * (lam * t) ** j / math.factorial(j) for j in range(k))

for t in [0.5, 1.5, 3.0]:
    print(f"P(T <= {t}): simulated {sum(x <= t for x in T) / n:.4f}  formula {gamma_cdf(t, k, lam):.4f}")
mean: 1.5009  k/lambda = 1.5
P(T <= 0.5): simulated 0.0804  formula 0.0803
P(T <= 1.5): simulated 0.5755  formula 0.5768
P(T <= 3.0): simulated 0.9376  formula 0.9380

The CDF formula uses a neat duality: the kk-th event happens by time tt exactly when at least kk events occur in [0,t][0, t], a Poisson count.

Beta: the distribution of a probability

The beta density on [0,1][0, 1] with parameters α,β>0\alpha, \beta > 0 is

f(p)=pα−1(1−p)β−1B(α,β)f(p) = \frac{p^{\alpha - 1}(1-p)^{\beta - 1}}{B(\alpha, \beta)}

where B(α,β)B(\alpha, \beta) normalises the area to 1. Its mean is αα+β\frac{\alpha}{\alpha + \beta}. Two stories:

  • Order statistics: the kk-th smallest of nn independent uniforms has the beta density with α=k\alpha = k, β=n−k+1\beta = n - k + 1.
  • Bayesian updating: with a uniform prior on a coin's bias pp, after hh heads and tt tails the posterior is beta with α=h+1\alpha = h + 1, β=t+1\beta = t + 1 (Bayes' Theorem).
python · try it yourself
import random

rng = random.Random(2)
n, k, runs = 9, 3, 50_000
third = [sorted(rng.random() for _ in range(n))[k - 1] for _ in range(runs)]
print("mean of 3rd smallest of 9 uniforms:", round(sum(third) / runs, 4), " beta mean k/(n+1) =", k / (n + 1))

# Bayesian A/B test: which button has the higher click rate?
a = [rng.betavariate(1 + 45, 1 + 955) for _ in range(runs)]     # 45 clicks of 1000
b = [rng.betavariate(1 + 62, 1 + 938) for _ in range(runs)]     # 62 clicks of 1000
print("P(B better than A) ~", round(sum(y > x for x, y in zip(a, b)) / runs, 3))
mean of 3rd smallest of 9 uniforms: 0.3004  beta mean k/(n+1) = 0.3
P(B better than A) ~ 0.953

The second part is a complete Bayesian A/B test: sample both posteriors and count how often B's click rate beats A's. This "probability to be best" is what many experimentation platforms report.

Chi-squared: sums of squared normals

If Z1,…,ZkZ_1, \ldots, Z_k are independent standard normals, Z12+⋯+Zk2Z_1^2 + \cdots + Z_k^2 has the chi-squared distribution with kk degrees of freedom, mean kk and variance 2k2k. It is a gamma density with shape k/2k/2 and rate 1/21/2. It measures squared distances: a random point from a kk-dimensional standard normal is at squared distance about kk from the origin, so in high dimensions Gaussian samples live near a sphere of radius k\sqrt{k}, not near the centre.

python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
for k in [1, 2, 10, 100, 1000]:
    z = rng.standard_normal((20_000, k))
    r = np.sqrt((z ** 2).sum(axis=1))
    print(f"k={k:5d}  mean |z|^2 = {np.mean(r ** 2):8.2f}   |z| between {np.quantile(r, 0.05):6.2f} and {np.quantile(r, 0.95):6.2f}   sqrt(k) = {np.sqrt(k):6.2f}")
k=    1  mean |z|^2 =     0.99   |z| between   0.06 and   1.94   sqrt(k) =   1.00
k=    2  mean |z|^2 =     1.99   |z| between   0.32 and   2.44   sqrt(k) =   1.41
k=   10  mean |z|^2 =    10.01   |z| between   1.99 and   4.28   sqrt(k) =   3.16
k=  100  mean |z|^2 =    99.95   |z| between   8.80 and  11.14   sqrt(k) =  10.00
k= 1000  mean |z|^2 =   999.57   |z| between  30.43 and  32.78   sqrt(k) =  31.62

The chi-squared distribution is the basis of the chi-squared test for counts, covered in Statistics.

In software

Gamma distributions model service times with several stages and are used in queueing simulations. Beta distributions drive Thompson sampling, the standard algorithm for multi-armed bandits in recommendation and ad systems: sample each arm's beta posterior and play the best sample. The "Gaussian samples lie on a shell" fact matters for embeddings and diffusion models in high dimensions (Math for ML).

Exercises

Exercise 1: Waiting for three

Calls arrive at rate 4 per minute. What are the mean and standard deviation of the time until the third call?

Answer

Mean 0.75 minutes, standard deviation about 0.43 minutes.

Solution

Gamma with k=3k = 3, λ=4\lambda = 4: mean 3/43/4, variance 3/163/16, standard deviation 3/4≈0.433\sqrt{3}/4 \approx 0.433.

Exercise 2: Beta posterior

With a uniform prior, a coin shows 7 heads in 10 tosses. What is the posterior distribution of pp and its mean?

Answer

Beta(8, 4) with mean 8/12=2/38/12 = 2/3.

Solution

α=h+1=8\alpha = h + 1 = 8, β=t+1=4\beta = t + 1 = 4; mean α/(α+β)\alpha/(\alpha + \beta).

Exercise 3: Thompson sampling (code)

Three ad variants have true click rates 0.04, 0.05 and 0.07, unknown to the algorithm. Run Thompson sampling for 5000 impressions and report how often each variant was shown.

Answer

The best variant (0.07) gets most of the impressions.

Solution

Each round, sample a click rate from each variant's beta posterior, show the variant with the highest sample, and update its counts.

python · try it yourself
import random

rng = random.Random(6)
true = [0.04, 0.05, 0.07]
wins = [0, 0, 0]
losses = [0, 0, 0]
shown = [0, 0, 0]
for _ in range(5000):
    samples = [rng.betavariate(1 + wins[i], 1 + losses[i]) for i in range(3)]
    i = samples.index(max(samples))
    shown[i] += 1
    if rng.random() < true[i]:
        wins[i] += 1
    else:
        losses[i] += 1
print("impressions:", shown)
print("observed rates:", [round(wins[i] / max(shown[i], 1), 3) for i in range(3)])
impressions: [473, 346, 4181]
observed rates: [0.042, 0.038, 0.067]

Test yourself

The time until the 5th event of a Poisson process with rate 2 has which distribution?

  1. Exponential with rate 10
  2. Gamma with k=5k = 5, λ=2\lambda = 2
  3. Poisson with mean 10
  4. Normal

With a uniform prior, the posterior of a coin's bias after 3 heads and 1 tail is…

  1. Beta(3, 1)
  2. Beta(4, 2)
  3. Beta(1, 3)
  4. Uniform

The sum of squares of kk independent standard normals has mean…

  1. 0
  2. 1
  3. kk
  4. k\sqrt{k}