From one try to many
Some distributions come up so often they have names. The simplest is one yes/no try that succeeds with chance p. X is 1 on success, 0 otherwise: a Bernoulli(p) variable. A fair coin flip, heads = 1, is Bernoulli(1/2).
Now repeat the try n = 4 times, each independent of the others. Every try has 2 results, so there are 2 × 2 × 2 × 2 = 16 sequences, from HHHH to TTTT. With p = 1/2 each sequence has chance 1/16.
Let X count the heads. How many sequences have exactly k heads? Choose which k of the 4 tries they are: C(4, k) ways, "4 choose k". That gives 1, 4, 6, 4, 1 sequences for k = 0 to 4: 16 in all.
The binomial distribution
Each sequence with k heads has chance pᵏ(1 − p)ⁿ⁻ᵏ. Multiply by the number of ways: P(X = k) = C(n, k) pᵏ(1 − p)ⁿ⁻ᵏ. That is the Binomial(n, p) distribution. Here P(X = 2) = 6 × 1/16 = 0.375.
The cumulative distribution function F(k) = P(X ≤ k) adds the bars from the left: 0.0625, 0.3125, 0.6875, 0.9375 and 1. It never goes down, and it ends at 1 because some value always happens.
X is a sum of 4 Bernoulli tries. Each has mean p and variance p(1 − p), and independent variances add. So E[X] = np = 2 and Var(X) = np(1 − p) = 1. The bars balance at 2.
Parameters and samples
n and p are the parameters: one formula, many shapes. Set p = 0.3 and the bars become 0.2401, 0.4116, 0.2646, 0.0756 and 0.0081. The peak moves to 1, and the mean drops to np = 1.2.
Python can draw from it: random.binomialvariate(4, 0.3), new in Python 3.12. With random.seed(1), 10,000 draws land 4,069 times on 1, a share of 0.4069. The formula said 0.4116: close, as expected.
In code, math.comb(n, k) counts the ways, and the formula does the rest. For n = 4, p = 0.3 and k = 1 there are 4 ways, so P(X = 1) = 4 × 0.3 × 0.7³ = 0.4116.
Try it in the Python prompt
;; step 1/9 · One try: Bernoulli >>> import random >>> random.seed(1) >>> [int(random.random() < 0.5) for _ in range(10)] # ten Bernoulli(1/2) draws [1, 0, 0, 1, 1, 1, 0, 0, 1, 1]
X ~ Binomial(n, p) is read "X follows a binomial distribution with n tries and success chance p". C(n, k) = n! / (k! (n − k)!) is the number of ways to choose k items from n. random.binomialvariate was added in Python 3.12. On older versions, sum(random.random() < p for _ in range(n)) draws the same distribution.