Random Variables
A random variable turns the outcome of an experiment into a number: the number of heads, the running time of a randomized algorithm, the number of keys in a hash bucket. Formally it is a function on the sample space. Once you have random variables you can talk about their distributions, their averages and how they combine.
Distributions
The probability density function (PDF) of a discrete random variable is , and its cumulative distribution function is . Common distributions in computer science:
| Distribution | Models | |
|---|---|---|
| Bernoulli() | one trial: success or not | for , for |
| uniform on | a fair die, a random index | |
| binomial() | successes in independent trials | |
| geometric() | trials until the first success | , |
from math import comb
n, p = 10, 0.3
pdf = [comb(n, k) * p ** k * (1 - p) ** (n - k) for k in range(n + 1)]
cdf, acc = [], 0.0
for v in pdf:
acc += v
cdf.append(acc)
for k in range(n + 1):
print(f"k={k:2d} P(R=k)={pdf[k]:.4f} P(R<=k)={cdf[k]:.4f} " + "#" * round(pdf[k] * 100))k= 0 P(R=k)=0.0282 P(R<=k)=0.0282 ###
k= 1 P(R=k)=0.1211 P(R<=k)=0.1493 ############
k= 2 P(R=k)=0.2335 P(R<=k)=0.3828 #######################
k= 3 P(R=k)=0.2668 P(R<=k)=0.6496 ###########################
k= 4 P(R=k)=0.2001 P(R<=k)=0.8497 ####################
k= 5 P(R=k)=0.1029 P(R<=k)=0.9527 ##########
k= 6 P(R=k)=0.0368 P(R<=k)=0.9894 ####
k= 7 P(R=k)=0.0090 P(R<=k)=0.9984 #
k= 8 P(R=k)=0.0014 P(R<=k)=0.9999
k= 9 P(R=k)=0.0001 P(R<=k)=1.0000
k=10 P(R=k)=0.0000 P(R<=k)=1.0000
The bars show the familiar hump of the binomial distribution, peaking near . See Binomial Probabilities for more.
Independence of random variables
and are independent if for all values the events and are independent. The number on the first die is independent of the number on the second; but the first die and the sum of both dice are not.
Hash bucket loads
Throw keys uniformly at random into buckets. The number of keys in bucket 1 is a sum of independent Bernoulli() indicators, so it is binomial(). With , the probability that bucket 1 is empty is : about 37% of the buckets stay empty, even though there are as many keys as buckets.
import random
from collections import Counter
rng = random.Random(42)
m = n = 10000
loads = Counter(rng.randrange(m) for _ in range(n))
dist = Counter(loads[b] for b in range(m))
for k in range(6):
print(f"buckets with {k} keys: {dist[k] / m:.4f}")
print("max load:", max(loads.values()))buckets with 0 keys: 0.3676
buckets with 1 keys: 0.3671
buckets with 2 keys: 0.1856
buckets with 3 keys: 0.0611
buckets with 4 keys: 0.0150
buckets with 5 keys: 0.0032
max load: 6
The fractions match the Poisson(1) probabilities : 0.368, 0.368, 0.184, 0.061, 0.015. The maximum load grows like , which is why hash table chains stay short.
Functions of random variables
If is a random variable, so is any , and sums and products of random variables are random variables. The running time of an algorithm is typically a sum of many simple random variables, which is what makes linearity of expectation so useful.
In software
Simulation code samples random variables (random.random() is a uniform variable on ), load balancers are analysed with balls-into-bins distributions, and network packet losses are modelled as Bernoulli trials. NumPy's numpy.random.Generator samples every distribution in the table above.
Exercises
Exercise 1: Distribution of a sum
Two fair dice; let be their sum. Find and .
Answer
; .
Solution
Sum 7: 6 of the 36 outcomes. Sum at most 4: sums 2, 3, 4 occur in outcomes.
Exercise 2: Geometric distribution
A request succeeds with probability 0.8, independently each try. What is the probability that the first success is on the third try? That more than 3 tries are needed?
Answer
; .
Solution
. More than 3 tries means the first 3 all fail: .
Exercise 3: Empty buckets (code)
Estimate the fraction of empty buckets when keys are thrown into buckets, and compare with .
Answer
About 0.135.
Solution
A bucket stays empty with probability .
import random, math
rng = random.Random(9)
m = 5000
used = {rng.randrange(m) for _ in range(2 * m)}
print(round(1 - len(used) / m, 4), round(math.exp(-2), 4))0.135 0.1353
Test yourself
Formally, a random variable is…
- a probability
- a function from the sample space to the real numbers
- an event
- a set of outcomes
The number of heads in 20 independent fair coin flips has which distribution?
- uniform
- geometric
- binomial(20, 1/2)
- Bernoulli(1/2)
With keys hashed into buckets, about what fraction of buckets stay empty?
- 0
- 50%