Lesson 6 of 18
Binomial Distribution
Counting Successes
The binomial distribution models the number of successes in independent trials, each with success probability . We write .
The PMF is:
P(X = k) = inom{n}{k} p^k (1-p)^{n-k}
import math
def binom_pmf(k, n, p):
return math.comb(n, k) * p**k * (1 - p)**(n - k)
def binom_cdf(k, n, p):
return sum(binom_pmf(i, n, p) for i in range(k + 1))
# Flip a fair coin 5 times. What is P(exactly 2 heads)?
n, p = 5, 0.5
print(round(binom_pmf(2, n, p), 4)) # 0.3125 — P(X = 2)
print(round(binom_cdf(2, n, p), 4)) # 0.5 — P(X <= 2)
PMF vs CDF
- PMF (probability mass function): — the probability of exactly successes
- CDF: — the probability of or fewer successes
Parameters
- — number of trials
- — probability of success per trial
- — number of successes to query
Example: Quality Control
In a factory, 10% of items are defective. If you inspect 20 items, what is the probability of finding exactly 2 defective ones?
print(round(binom_pmf(2, n=20, p=0.1), 4)) # 0.2852
Your Task
Implement binomial_stats(n, p, k) that prints:
- — the PMF (rounded to 4 decimal places)
- — the CDF (rounded to 4 decimal places)
Pyodide loading...
Loading...
Click "Run" to execute your code.