Lesson 6 of 18

Binomial Distribution

Counting Successes

The binomial distribution models the number of successes in nn independent trials, each with success probability pp. We write XsimextBinomial(n,p)X sim ext{Binomial}(n, p).

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): P(X=k)P(X = k) — the probability of exactly kk successes
  • CDF: P(Xleqk)P(X leq k) — the probability of kk or fewer successes

Parameters

  • nn — number of trials
  • pp — probability of success per trial
  • kk — 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:

  1. P(X=k)P(X = k) — the PMF (rounded to 4 decimal places)
  2. P(Xleqk)P(X leq k) — the CDF (rounded to 4 decimal places)
Pyodide loading...
Loading...
Click "Run" to execute your code.