For events A1, ..., An, Theorem 2.3.7 writes P(A1 ∪ ... ∪ An) = S1 − S2 + S3 − ..., where Sj adds the probabilities of all j-fold intersections. Stopping after J terms gives the partial sum TJ: odd J overshoot the union, even J undershoot it (the Bonferroni inequalities). The top panel plots TJ (gold) against the exact union (teal dashed); the bottom panel simulates the number of events that occur, whose zero class is the complement of the union. Matching: n letters are put at random into n envelopes and Ai says letter i is correct; then Sj = 1/j! for every n.
Independent events: Sj = C(n,j)pj and the union has probability 1 − (1 − p)n. Matching: the number of letters in the right envelope has, for large n, nearly the Poisson distribution with mean 1, and the probability that at least one is right tends to 1 − 1/e = 0.6321. The simulation of the matching problem shuffles the letters with the Fisher–Yates method.
code/ch02_probability.py (incl_excl_partial, derangements, matching_union, demo_matching, demo_independent).