NumPy Binomial Distribution
The binomial distribution models the number of successes in a fixed number of independent yes/no trials, and np.random.binomial simulates exactly that.
What Is a Binomial Experiment?
A binomial experiment consists of a fixed number of independent trials, where each trial has exactly two possible outcomes - success or failure - and the probability of success stays the same across every trial. Flipping a coin 10 times and counting heads is a binomial experiment, and so is checking 100 customers where each independently has a 30 percent chance of making a purchase.
Example
import numpy as np
np.random.seed(30)
# Flip a fair coin 10 times and count the heads, once
heads_count = np.random.binomial(n=10, p=0.5, size=1)
print(heads_count)The n and p Parameters
np.random.binomial(n, p, size) takes n as the number of trials in a single experiment, p as the probability of success on each trial (a value between 0 and 1), and size as how many independent experiments to run. Every value in the returned array is the count of successes from one full experiment, so each result is always a whole number between 0 and n.
Example
import numpy as np
np.random.seed(31)
# Run 10 experiments, each flipping a fair coin 20 times
results = np.random.binomial(n=20, p=0.5, size=10)
print(results)
print("Average heads per experiment:", np.mean(results))Binomial vs Normal Distribution
The binomial distribution is discrete - it only ever produces whole-number counts of successes - while the normal distribution from the previous lesson is continuous. Even so, the two are closely related: as n grows large, the shape of the binomial distribution starts to look increasingly like a bell-shaped normal curve centered around n times p.
- Estimating conversions in an A/B test out of a fixed number of visitors.
- Counting defective items in a fixed-size manufacturing batch.
- Modeling pass/fail results in quality control sampling.
- Simulating made free throws out of a fixed number of attempts.
- Estimating how many recipients open a marketing email out of those sent.
Example
import numpy as np
np.random.seed(32)
# 100 days, 50 sales calls each day, 20% chance to close each call
closed_deals = np.random.binomial(n=50, p=0.2, size=100)
print("Simulated average closes per day:", np.mean(closed_deals))
print("Expected value (n * p):", 50 * 0.2)Exercise: NumPy Binomial Distribution
Which two parameters describe a distribution in np.random.binomial()?