Sign in

Basic probability

A finite sample space with one probability per outcome, and the rules that turn those numbers into the probability of any event.

Overview

Start with a list of everything that can happen, such as the six faces of a die. Give each outcome a share of certainty, so that the shares add up to 1. An event is a set of outcomes, and its probability is the sum of their shares. Every other rule follows from that: the chance an event does not happen, the chance that either of two events happens, and the chance that both do. Counting helpers answer how many outcomes there are when listing them by hand is too slow.

A short history

Probability as a calculation began with letters between Blaise Pascal and Pierre de Fermat in 1654 about how to divide the stakes of an unfinished game of chance. Jacob Bernoulli and Pierre-Simon Laplace turned those ideas into a general theory. In 1933 Andrey Kolmogorov gave the three axioms used today, which put probability on the same footing as the rest of mathematics.

How it works

  1. List the outcomes of the experiment. This list is the sample space Ω\Omega, and the outcomes must be distinct.
  2. Give each outcome a probability p(ω)≥0p(\omega) \ge 0 so that all of them sum to 1. With no probabilities given, the template makes every outcome equally likely.
  3. Describe an event AA as a set of outcomes, or as a rule that says yes or no for each outcome.
  4. Add the probabilities of the outcomes inside the event to get P(A)P(A).
  5. Combine events: the complement is everything outside AA, the intersection is the outcomes in both events, the union is the outcomes in at least one.
  6. Test independence by comparing P(A∩B)P(A \cap B) with P(A) P(B)P(A)\,P(B). Equal means that knowing one event tells you nothing about the other.
  7. For several independent experiments run together, build the product space: outcomes are tuples and their probabilities multiply.

Watch out for

  • Adding P(A)P(A) and P(B)P(B) for a union counts the overlap twice. Subtract P(A∩B)P(A \cap B) unless the events cannot happen together.
  • Mutually exclusive and independent are different ideas. Two exclusive events with positive probability are never independent, because one happening rules the other out.
  • Treating outcomes as equally likely when they are not gives wrong answers. The sums 2 and 7 of two dice are both single values, but 7 can occur in six ways and 2 in one.
  • The template lists every outcome, so a product of many spaces grows very fast. Ten dice already give about 60 million tuples.

Use cases

When to use it

Checking a probability claim by building the sample space and counting, and as the base for every later topic: conditional probability, random variables and distributions all rest on these rules.

In industry

Insurance
Actuaries estimate the chance of a claim per policy from past records, then set premiums so expected payouts are covered.
Manufacturing quality control
A plant inspects a sample from each batch and uses the probability of finding defects to decide whether to accept the whole batch.
Machine learning
A classifier outputs one probability per class that sums to 1, and decisions such as spam or not spam are made by comparing those numbers.

Choosing it: what must hold

  • A list of outcomes that are mutually exclusive and together cover everything that can happen.
  • A probability for each outcome, from counting equally likely cases or from frequencies in enough data.
  • A finite or countable set of outcomes. Measurements on a continuous scale need densities instead.

When to choose something else

IfUse instead
The quantity is a measurement on a continuous scaleRandom variables, with densities and integrals
You need the chance of an event given that another has happenedConditional probability
Two variables must be described togetherJoint and marginal probability

Math foundations

  1. The axioms

    P(A)≥0,P(Ω)=1,P(A∪B)=P(A)+P(B)  if A∩B=∅P(A) \ge 0, \qquad P(\Omega) = 1, \qquad P(A \cup B) = P(A) + P(B) \ \text{ if } A \cap B = \emptyset

    Three rules define a probability: it is never negative, the whole sample space has probability 1, and the probabilities of events that cannot happen together add.

  2. Probability of an event

    P(A)=∑ω∈Ap(ω)P(A) = \sum_{\omega \in A} p(\omega)

    On a finite space an event is a set of outcomes, and its probability is the sum of their individual probabilities. This is what the method prob computes.

  3. Complement

    P(Ac)=1−P(A)P(A^{c}) = 1 - P(A)

    An event and its complement cover the whole space without overlap, so their probabilities sum to 1. It is often easier to compute the chance that something never happens and subtract.

  4. Addition rule

    P(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B)

    Outcomes that lie in both events are counted once in P(A)P(A) and once in P(B)P(B), so the overlap is removed once.

  5. Independence

    P(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B)

    The definition of independent events. The template tests it within the configured tolerance, because sums of floating point numbers are rarely exact.

  6. Counting

    nPk=n!(n−k)!,(nk)=n!k! (n−k)!{}^{n}P_{k} = \frac{n!}{(n-k)!}, \qquad \binom{n}{k} = \frac{n!}{k!\,(n-k)!}

    The number of ordered arrangements of kk items chosen from nn, and the number of unordered selections. When all outcomes are equally likely, a probability is a count of favourable outcomes divided by a count of all outcomes.

  7. The birthday problem

    P(shared)=1−∏i=0m−1(1−id)P(\text{shared}) = 1 - \prod_{i=0}^{m-1}\left(1 - \frac{i}{d}\right)

    The chance that at least two of mm people share one of dd equally likely days. The product is the chance that every person in turn misses all the days already taken, which is the complement rule at work.

Symbols

Ω\Omega
the sample space: the set of all outcomes
ω\omega
one outcome
p(ω)p(\omega)
the probability of outcome ω\omega
A, BA,\ B
events, which are sets of outcomes
AcA^{c}
the complement of AA: every outcome not in AA
A∩BA \cap B
the intersection: outcomes in both events
A∪BA \cup B
the union: outcomes in at least one of the events
n, kn,\ k
the number of items available and the number chosen
m, dm,\ d
the number of people and the number of possible days

Worked by hand

Roll two fair dice, so there are 36 equally likely pairs. Let AA be the event that the sum is 7 and BB the event that the first die shows 3. Six pairs sum to 7, six pairs start with 3, and only the pair (3,4)(3, 4) does both.

P(A)=636=16,P(B)=636=16,P(A∩B)=136P(A) = \frac{6}{36} = \frac{1}{6}, \qquad P(B) = \frac{6}{36} = \frac{1}{6}, \qquad P(A \cap B) = \frac{1}{36}
P(A∪B)=636+636−136=1136≈0.306P(A \cup B) = \frac{6}{36} + \frac{6}{36} - \frac{1}{36} = \frac{11}{36} \approx 0.306
P(A) P(B)=16×16=136=P(A∩B)P(A)\,P(B) = \frac{1}{6} \times \frac{1}{6} = \frac{1}{36} = P(A \cap B)

The union has probability 11/36, and the two events are independent: learning that the first die is 3 leaves the chance of a sum of 7 at 1/6.

Visual example

Loading the example.

Try this

  • Keep the sum at 7 and move d: a sum of 7 stays independent of what the first die shows.
  • Change the sum to 8 and the two events stop being independent.
  • Load the first die toward six and watch every cell in the bottom row gain probability.

Code sample

from impl import ProbabilitySpace, n_combinations

die = ProbabilitySpace(range(1, 7))
two = ProbabilitySpace.product(die, die)             # 36 ordered pairs
p7 = two.prob(lambda o: o[0] + o[1] == 7)            # 1/6
either = two.union(lambda o: o[0] == 6, lambda o: o[1] == 6)   # 11/36
hands = n_combinations(52, 5)                        # 2598960 poker hands
Read the implementation (126 lines)
"""Basic probability on a finite sample space.

`ProbabilitySpace` holds a list of outcomes and the probability of each, and answers the questions the axioms
allow: the probability of an event, of its complement, of a union or an intersection, whether two events are
independent or mutually exclusive. Counting helpers cover permutations, combinations and the birthday problem.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import BasicProbabilityConfig
except ImportError:  # run from the template's own folder
    from config import BasicProbabilityConfig

class ProbabilitySpace:
    """A finite sample space: distinct outcomes and one probability per outcome.

    outcomes:      list of hashable outcomes, length n.
    probabilities: array (n,) of non-negative numbers summing to 1; None means all outcomes are equally likely.

    An event is either a function `outcome -> bool` or a collection (set, list) of outcomes.
    """

    def __init__(self, outcomes, probabilities=None, config: BasicProbabilityConfig | None = None) -> None:
        self.config = config or BasicProbabilityConfig()
        self.outcomes = list(outcomes)
        n = len(self.outcomes)
        if n == 0:
            raise ValueError("the sample space needs at least one outcome")
        if len(set(self.outcomes)) != n:
            raise ValueError("outcomes must be distinct")
        p = np.full(n, 1.0 / n) if probabilities is None else np.asarray(probabilities, dtype=float)
        if p.shape != (n,):
            raise ValueError(f"probabilities must have shape ({n},), got {p.shape}")
        if np.any(p < 0):
            raise ValueError("probabilities must be non-negative")
        total = float(p.sum())
        if self.config.normalize:
            if total <= 0:
                raise ValueError("probabilities sum to zero, nothing to normalize")
            p = p / total
        elif abs(total - 1.0) > self.config.tolerance:
            raise ValueError(f"probabilities must sum to 1, got {total}")
        self.probabilities = p

    @classmethod
    def product(cls, *spaces: "ProbabilitySpace", config: BasicProbabilityConfig | None = None) -> "ProbabilitySpace":
        """Space of independent experiments run together. Outcomes are tuples, one entry per space."""
        outcomes, probs = [()], np.ones(1)
        for space in spaces:
            outcomes = [o + (new,) for o in outcomes for new in space.outcomes]
            probs = np.outer(probs, space.probabilities).ravel()
        return cls(outcomes, probs, config)

    def mask(self, event) -> np.ndarray:
        """Boolean array (n,): True where the outcome belongs to the event."""
        if callable(event):
            return np.array([bool(event(o)) for o in self.outcomes])
        members = set(event)
        unknown = members - set(self.outcomes)
        if unknown:
            raise ValueError(f"event holds outcomes outside the sample space: {sorted(map(repr, unknown))}")
        return np.array([o in members for o in self.outcomes])

    def prob(self, event) -> float:
        """P(A): the sum of the probabilities of the outcomes in the event."""
        return float(self.probabilities[self.mask(event)].sum())

    def complement(self, event) -> float:
        """P(not A) = 1 - P(A)."""
        return float(self.probabilities[~self.mask(event)].sum())

    def intersection(self, a, b) -> float:
        """P(A and B)."""
        return float(self.probabilities[self.mask(a) & self.mask(b)].sum())

    def union(self, a, b) -> float:
        """P(A or B) = P(A) + P(B) - P(A and B)."""
        return float(self.probabilities[self.mask(a) | self.mask(b)].sum())

    def conditional(self, a, given) -> float:
        """P(A | B) = P(A and B) / P(B). Raises ValueError when P(B) is zero."""
        p_b = self.prob(given)
        if p_b == 0:
            raise ValueError("cannot condition on an event of probability zero")
        return self.intersection(a, given) / p_b

    def independent(self, a, b) -> bool:
        """True when P(A and B) = P(A) P(B) within the configured tolerance."""
        return abs(self.intersection(a, b) - self.prob(a) * self.prob(b)) <= self.config.tolerance

    def mutually_exclusive(self, a, b) -> bool:
        """True when no outcome with positive probability lies in both events."""
        return self.intersection(a, b) <= self.config.tolerance

    def odds(self, event) -> float:
        """Odds in favour of the event: P(A) / P(not A). Infinite when the event is certain."""
        p = self.prob(event)
        return math.inf if p >= 1.0 else p / (1.0 - p)

    def expectation(self, value) -> float:
        """E[f] for a function `outcome -> number`: the probability-weighted average of its values."""
        return float(np.dot(self.probabilities, [float(value(o)) for o in self.outcomes]))


def n_permutations(n: int, k: int | None = None) -> int:
    """Number of ordered arrangements of k items chosen from n: n! / (n - k)!. k defaults to n."""
    return math.perm(n, n if k is None else k)


def n_combinations(n: int, k: int) -> int:
    """Number of unordered selections of k items from n: n! / (k! (n - k)!)."""
    return math.comb(n, k)


def birthday_collision_probability(people: int, days: int = 365) -> float:
    """Probability that at least two of `people` share a birthday when all `days` are equally likely."""
    if people < 0 or days <= 0:
        raise ValueError("people must be >= 0 and days > 0")
    if people > days:
        return 1.0
    no_match = np.prod(1.0 - np.arange(people) / days)
    return float(1.0 - no_match)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Build one die with ProbabilitySpace(range(1, 7)) and two dice with ProbabilitySpace.product(die, die). Use prob, union and independent to reproduce the worked example with events written as functions of the tuple. Then replace the sum of 7 by a sum of 8 and check independence again. Finish with birthday_collision_probability(23).

Check on learning

  1. A sum of 7 is independent of the first die showing 3, but a sum of 8 is not. What is different about 8?
    A way to think about it

    Ask whether every value of the first die leaves the same number of ways to finish. For a sum of 8, what happens when the first die shows 1?

  2. Two events each have probability 0.6. What are the smallest and largest values their intersection can take, and why can it not be zero?
    A way to think about it

    Use the addition rule together with the fact that no union can exceed 1. Then ask what the most complete overlap would look like.

  3. With 23 people the chance of a shared birthday is already above one half, although 23 is far smaller than 365. Why does intuition miss this?
    A way to think about it

    Count the pairs of people, not the people. Each pair is a separate chance of a match, and (232)\binom{23}{2} is much larger than 23.

  4. You set normalize to true and pass the weights 2, 1, 1 for three outcomes. What space do you get, and when would silently rescaling be a bad idea?
    A way to think about it

    Divide by the total to see the probabilities. Then think about a typing mistake in a list that was meant to sum to 1: would you want an error or a quiet fix?