AI Wiki中文/EN

Bernoulli and binomial distributions

伯努利与二项分布

Derive counts from independent binary trials, distinguish sequences from events, and compute exact probabilities including endpoints.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

One outcome or a count of outcomes?

Suppose a teaching model says each of four independent requests fails with probability 1/41/4. Record failure as 1 and completion as 0. A single request has two outcomes, described by a Bernoulli distribution. The total number of failures can be 0, 1, 2, 3, or 4, described by a binomial distribution.

The particular sequence 1,1,0,01,1,0,0 has probability 9/2569/256. “Exactly two failures” has probability 54/25654/256, six times larger: the two failures can occupy any two of four positions. Confusing a sequence with a count loses these possibilities. The model is hypothetical; a service outage that makes requests fail together would violate its independence assumption.

Build the count from indicators

A Bernoulli random variable BB takes value 1 with probability pp and value 0 with probability 1−p1-p, where 0≤p≤10\le p\le1. The word “success” often labels value 1; it can equally well mean a failure, a click, or a correct prediction. For 0<p<10<p<1, its probability mass function is:

P(B=b)=pb(1−p)1−b,b∈{0,1}.P(B=b)=p^b(1-p)^{1-b},\qquad b\in\{0,1\}.

Outside these values the probability is zero. At p=0p=0, B=0B=0 almost surely; at p=1p=1, B=1B=1 almost surely. Stating endpoints separately avoids an unexplained 000^0. Since B2=BB^2=B, its first two moments give:

E[B]=p,Var⁡(B)=E[B2]−E[B]2=p(1−p).E[B]=p,\qquad \operatorname{Var}(B)=E[B^2]-E[B]^2=p(1-p).

Now fix a nonnegative integer nn and take mutually independent Bernoulli variables B1,…,BnB_1,\ldots,B_n, all with this same pp. Their sum KK has the binomial distribution Bin⁡(n,p)\operatorname{Bin}(n,p). These assumptions concern the joint experiment, not just the fact that outcomes are binary. Berkeley Statistics 240, discrete distributions

For 0<p<10<p<1, a specified sequence containing kk ones has probability pk(1−p)n−kp^k(1-p)^{n-k} by independence. Choosing its kk one-positions produces (nk)\binom nk disjoint sequences. Adding their probabilities yields:

P(K=k)=(nk)pk(1−p)n−k,(nk)=n!k!(n−k)!,k=0,…,n.P(K=k)=\binom nk p^k(1-p)^{n-k},\qquad \binom nk=\frac{n!}{k!(n-k)!},\qquad k=0,\ldots,n.

The binomial theorem verifies that these masses sum to (p+(1−p))n=1(p+(1-p))^n=1. For p=0p=0 all mass is at 0; for p=1p=1 all mass is at nn. We include the useful empty experiment n=0n=0: its sum is 0 and its distribution is a point mass there for every pp. A PMF gives the probability at an integer; it is not a continuous density. NIST, binomial PMF

Linearity of expectation adds the means even without independence. Independence additionally removes the cross-covariances in the variance of the sum:

E[K]=np,Var⁡(K)=np(1−p),Var⁡(K/n)=p(1−p)n(n>0).E[K]=np,\qquad \operatorname{Var}(K)=np(1-p),\qquad \operatorname{Var}(K/n)=\frac{p(1-p)}{n}\quad(n>0).

In the four-request model the expected count is 1, variance is 3/43/4, and the probability of at least one failure is 1−(3/4)4=175/2561-(3/4)^4=175/256. An expected count of 1 does not say that exactly one failure will occur. The variance of a proportion shrinks with nn, while the variance of the count grows with nn when pp is fixed in (0,1)(0,1).

Let each trial update the probability table

Instead of evaluating factorials, build the distribution one trial at a time. Write qi(k)q_i(k) for the probability of kk ones in the first ii trials. There are two disjoint ways to end at kk: have kk already and observe 0, or have k−1k-1 and observe 1. Thus:

qi(k)=(1−pi)qi−1(k)+piqi−1(k−1),q0(0)=1.q_i(k)=(1-p_i)q_{i-1}(k)+p_iq_{i-1}(k-1),\qquad q_0(0)=1.

Undefined count positions have mass zero. The recurrence assumes independence from the previous trials. It works for different probabilities pip_i as well as for the common-pp binomial case. The following complete program uses exact fractions and explicitly separates ordered_probability from the count PMF.

from fractions import Fraction as F

def probability(p):
    if type(p) is not int and not isinstance(p,F):
        raise ValueError("use an integer or Fraction probability")
    p = F(p)
    if not 0 <= p <= 1:
        raise ValueError("probability must lie in [0,1]")
    return p

def count_pmf(probabilities):
    # Independent Bernoulli trials; probabilities may differ.
    mass = [F(1)]
    for value in probabilities:
        p = probability(value)
        next_mass = [F(0)] * (len(mass)+1)
        for k, old in enumerate(mass):
            next_mass[k] += old*(1-p)
            next_mass[k+1] += old*p
        mass = next_mass
    return mass

def binomial_pmf(n,p):
    if type(n) is not int or n < 0:
        raise ValueError("n must be a nonnegative integer")
    p = probability(p)
    return count_pmf([p]*n)

def ordered_probability(outcomes,p):
    p = probability(p)
    value = F(1)
    for bit in outcomes:
        if type(bit) is not int or bit not in (0,1):
            raise ValueError("each outcome must be integer 0 or 1")
        value *= p if bit else 1-p
    return value

mass = binomial_pmf(4,F(1,4))
assert mass == [F(v,256) for v in [81,108,54,12,1]]
assert ordered_probability([1,1,0,0],F(1,4)) == F(9,256)
assert mass[2] == 6*F(9,256)
assert sum(mass) == 1
assert sum(k*p for k,p in enumerate(mass)) == 1
assert sum((k-1)**2*p for k,p in enumerate(mass)) == F(3,4)
assert binomial_pmf(0,F(1,4)) == [1]
assert binomial_pmf(3,0) == [1,0,0,0]
assert binomial_pmf(3,1) == [0,0,0,1]
assert count_pmf([F(1,10),F(9,10)]) == [F(9,100),F(82,100),F(9,100)]

Computing all n+1n+1 masses this way takes O(n2)O(n^2) arithmetic operations and O(n)O(n) peak storage. Exact fraction bit costs increase with input size. It is a transparent small-example algorithm, not a fast production routine for millions of trials. For large numerical calculations, use established distribution routines with log probabilities or survival functions: a naive product can underflow, and subtracting a CDF from 1 can lose a small upper-tail probability. The exact table here is useful as a reference for testing moderate numerical cases.

Check the experiment before choosing the formula

Binary outcomes alone do not make a binomial count. If independent trials have different fixed probabilities, the sum is a Poisson-binomial variable. For two probabilities 1/101/10 and 9/109/10, the masses at 0, 1, 2 are 9/100,82/100,9/1009/100,82/100,9/100. Its mean is 1 but variance is 18/10018/100; replacing both probabilities with their average 1/21/2 keeps the mean and changes the variance to 1/21/2. The general definition permits unequal Bernoulli probabilities. Daskalakis, Diakonikolas and Servedio, abstract, revised 2015 version

Dependence breaks a different assumption. Let both outcomes equal the same fair Bernoulli variable. The total is 0 or 2 with probability 1/21/2 each; exactly one success is impossible. Each outcome individually has p=1/2p=1/2, yet the count is not Bin⁡(2,1/2)\operatorname{Bin}(2,1/2). Its variance is 1, twice the binomial variance. Repeated predictions on closely related examples can require examining such shared sources of variation.

Sampling without replacement from a finite population has another count law. Choose two objects uniformly from four, of which two are marked. There are six equally likely subsets: one has no marked objects, four have one, and one has two. The probabilities are therefore 1/6,4/6,1/61/6,4/6,1/6, not the binomial values 1/4,1/2,1/41/4,1/2,1/4. This is a hypergeometric experiment. Berkeley Statistics 240, sampling without replacement

A random stopping rule also changes what is observed: “count successes in ten trials” differs from “count trials until the third success.” Before fitting a parameter, write down whether nn is fixed and what the sample space contains. In a classifier evaluation, binomial reasoning can describe independent examples drawn from a fixed population under a fixed model. The formula alone cannot justify that sampling description or transfer the resulting performance to a different population.

Keep the event in view

  1. In the four-request model, what is the probability that only the second request fails? Answer: (1/4)(3/4)3=27/256(1/4)(3/4)^3=27/256. Exactly one failure anywhere has four times that probability, 108/256108/256.
  2. What changes when the recorded bit means completion instead of failure? Answer: the new count is 4−K∼Bin⁡(4,3/4)4-K\sim\operatorname{Bin}(4,3/4), with mean 3 and the same variance 3/43/4.
  3. Can Bin⁡(0,p)\operatorname{Bin}(0,p) observations identify pp? Answer: no. The sole count is always zero with probability 1, for every pp. No trial supplies information about its outcome probability.
  4. Two trials share the same fair outcome. Is their mean count still np=1np=1? Answer: yes; linearity needs no independence. Their count variance is 1, so the binomial variance 1/21/2 is wrong.

From outcome probabilities to learning losses

For a fixed observed sequence of length n>0n>0 with kk ones, its likelihood as a function of pp is pk(1−p)n−kp^k(1-p)^{n-k}. The count likelihood has an additional factor (nk)\binom nk, constant in pp. They therefore have the same maximizing value p^=k/n\hat p=k/n, including the all-zero and all-one endpoints. For an interior optimum, differentiating the log likelihood gives k/p−(n−k)/(1−p)=0k/p-(n-k)/(1-p)=0. NIST, parameter estimation

For a single label bb, negating the log likelihood gives the binary cross-entropy expression −blog⁡p−(1−b)log⁡(1−p)-b\log p-(1-b)\log(1-p) for 0<p<10<p<1. A model may supply a different conditional probability for each input; that training objective does not require pretending all examples have the same conditional pp. Estimation uncertainty, dependence, and probability calibration need their own checks. Start by changing the probabilities in count_pmf, and see which summaries survive the change: equal expected counts can conceal very different risks.

Make a prediction, then check

Four independent trials each succeed with probability 1/4. What is the probability of exactly two successes?

Choose one answer

Learning objectives

  • Separate a single Bernoulli outcome, an ordered sequence, and a binomial count event, deriving the combinatorial factor.
  • Derive mean and variance, handle p=0, p=1 and n=0, and compute a complete PMF with an exact recurrence.
  • Identify how unequal probabilities, dependence, sampling without replacement, and random stopping change a binomial experiment.

Prerequisites & connections

Explore related knowledge →

References

  1. Statistics 240 — Some Discrete Distributions
    Philip B. Stark
  2. NIST/SEMATECH e-Handbook — Binomial Distribution
    NIST and SEMATECH
  3. Learning Poisson Binomial Distributions (v4, revised 17 February 2015)
    Constantinos Daskalakis; Ilias Diakonikolas; Rocco A. Servedio · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.

  • Compared inspected Berkeley/NIST course material and documentation plus the Poisson-binomial abstract, separating common fixed p, mutual independence, integer n, and endpoint point masses.
  • Enumerated every binary sequence for n=0 through 8 and five exact probabilities, checking the recurrence against independent probability products, combinatorial factors, normalization, mean, variance and complement symmetry.
  • Matched random unequal-probability recurrences to full joint enumeration; checked hypergeometric and fully dependent countermodels, empty sequences and input errors, then compared both languages and four answers.
  • Independent cross-review checked common probability, mutual independence, the combinatorial factor, n=0/p=0/p=1, non-binomial counterexamples, and complexity; sources and six tests were separately checked.
  • The parent executed all 25 independent probability checks; bilingual code, display equations, main anchors, sources and exercises were additionally compared.
  • Static rendering found unprocessed answer emphasis adjacent to Chinese text; explicit strong tags now preserve all answer text, values and formulas.

Source locations checked:

  • Statistics 240 — Some Discrete Distributions · Some discrete distributions: Bernoulli trials and mutual independence, n independent trials with common p, binomial count PMF, and finite-population simple random sampling without replacement with the hypergeometric PMF. Author verified at the linked Philip B. Stark faculty homepage.
  • NIST/SEMATECH e-Handbook — Binomial Distribution · Section 1.3.6.6.18, Probability Mass Function, Common Statistics and Parameter Estimation: binomial coefficient, fixed common p, mean np, standard deviation sqrt(np(1−p)), and MLE k/n. The article states independence and n=0/endpoint conventions explicitly rather than importing incomplete assumptions.
  • Learning Poisson Binomial Distributions (v4, revised 17 February 2015) · arXiv:1107.2702, v4 dated 2015-02-17: inspected abstract definition of a sum of independent Bernoulli variables allowing unequal expectations; metadata and version history inspected. No full-paper algorithm or bound claims used.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.