Lesson 10 of 15

Bernoulli & Binomial Distributions

Counting Successes

A Bernoulli(pp) trial has two outcomes: success (probability pp) and failure (probability 1p1-p).

A Binomial(nn, pp) random variable counts successes in nn independent Bernoulli trials:

P(X=k)=(nk)pk(1p)nkP(X = k) = \binom{n}{k} p^k (1-p)^{n-k}

E[X]=np,Var(X)=np(1p)E[X] = np, \qquad \text{Var}(X) = np(1-p)

The (nk)\binom{n}{k} factor counts the number of ways to arrange kk successes in nn positions.

import math

def binom_pmf(n, p, k):
    return math.comb(n, k) * p**k * (1 - p)**(n - k)

def binom_cdf(n, p, k):
    return sum(binom_pmf(n, p, i) for i in range(k + 1))

# P(exactly 3 heads in 10 fair flips)
print(round(binom_pmf(10, 0.5, 3), 4))   # 0.1172
print(round(binom_cdf(10, 0.5, 3), 4))   # 0.1719

Why This Distribution Is Everywhere

  • Quality control: number of defective items in a batch
  • Clinical trials: number of patients who respond to treatment
  • Surveys: number of yes responses out of nn respondents
  • A/B testing: number of conversions out of nn visitors

Your Task

Implement binomial_full(n, p, k) that prints PMF(k)(k), CDF(k)(k), E[X]E[X], and Var(X)\text{Var}(X), each rounded to 4 decimal places.

Pyodide loading...
Loading...
Click "Run" to execute your code.