12/17
Part 6 of 7 · The worked exampleLearn

An expected iterations question, as a coding round asks it

The second one comes from a coding round.

This function draws random points in the unit square until one lands inside the quarter circle. How many iterations does it run on average?

The method: find the chance one pass ends the loop, check that every pass has the same chance independently, and take one over it. Here a pass ends the loop when the point lands in the quarter circle, an area of π/4.

import math
import random

rng = random.Random(4)


def iterations():
    """Draws points in the unit square until one lands inside the quarter circle."""
    count = 1
    while rng.random() ** 2 + rng.random() ** 2 > 1:
        count += 1
    return count


average = sum(iterations() for _ in range(100_000)) / 100_000
print(f"{average:.3f} iterations on average")
Predict

What's the expected number of iterations?

Pick one to see what it prints.
Pick an answer above to see the rest