Events and Probability Spaces · Monte Carlo Simulation
Lesson 2
In code, a random experiment can be represented by a function returning an outcome, and an event by a function returning either \(\texttt{True}\) or \(\texttt{False}\). Then the Monte Carlo estimator is almost embarrassingly simple.
import random
def probability(experiment, event, trials):
hits = 0
for _ in range(trials):
if event(experiment()):
hits += 1
return hits / trials
def flip_30_coins():
return random.choices(["H", "T"], k=30)
def at_least_20_heads(outcome):
return outcome.count("H") >= 20
random.seed(1)
print(probability(flip_30_coins, at_least_20_heads, 100_000))0.04985
This program does not prove the exact value of the probability, but it gives a useful estimate. In practice, this is often enough to test intuition, to check a formula, or to choose between two engineering decisions before doing a more careful analysis.