Darts in the Unit Square

Information Theory & Stochastic ProcessesMedium+20 XP+20

Darts in the Unit Square

When a number is hard to calculate exactly, Monte Carlo simulation generates lots of random examples and lets the pattern in them reveal it. Here the number is π\piπ.

Throw darts uniformly at random into the unit square, 0≤x<10 \le x < 10≤x<1 and 0≤y<10 \le y < 10≤y<1. A dart lands inside the quarter circle of radius 111 when x2+y2≤1x^2 + y^2 \le 1x2+y2≤1. The fraction of darts that land inside settles toward the quarter circle's share of the square's area — and from that fraction you can estimate π\piπ.

Task: write estimate_pi(seed, checkpoints), which throws darts one at a time and returns the running estimate of π\piπ at each checkpoint.

  • Make the random numbers with rng = random.Random(seed). For each dart, call rng.random() twice: the first value is xxx, the second is yyy.
  • checkpoints is a list of dart counts in increasing order, e.g. [10, 100, 1000]. At each checkpoint, report the estimate based on every dart thrown so far.
  • Throw exactly as many darts as the last checkpoint — the judge replays the same darts from the seed.
  • Return one estimate per checkpoint, each rounded to 4 decimal places.

Watch the estimates as the checkpoints grow. Their drift toward 3.14163.14163.1416 is the Law of Large Numbers at work, and how slowly they get there — the error shrinks only like 1/N1/\sqrt{N}1/N​ — is why Monte Carlo needs so many samples.

Monte Carlo

Monte Carlo Estimation

Throw random darts at a square. The probability of landing in the inscribed circle is π/4. Compute π ≈ 4 × (Inside / Total).

Total Darts0
Inside Circle0
Pi Estimate0.00000
Absolute Error0.00000
According to the Law of Large Numbers, the error decreases at a slow rate of O(1 / √N). Note that throwing more samples yields highly stable values.

Examples

seed = 1
checkpoints = [10, 100, 1000]
returns [3.6, 3.2, 3.112]
seed = 42
checkpoints = [1, 4, 16, 64]
returns [4.0, 3.0, 2.75, 2.9375]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run