#582 · Modules and random · Intermediate · 60 XP · about 10 min
Picture a square board from -1 to 1 in both directions, with a circle of radius 1 drawn inside it. Throw darts that land at random spots on the board. The circle covers pi / 4 of the square, so about pi / 4 of the darts land inside it, and 4 times the fraction that lands inside is close to pi.
Write estimate_pi(darts) that throws darts random darts and returns 4 * inside / darts as a float, where inside counts the darts whose distance from the center is at most 1. random.uniform(-1, 1) gives a random coordinate, and math.hypot(x, y) gives the distance of the point (x, y) from the center.
estimate_pi(100000) # returns a value close to 3.14, such as 3.14232 estimate_pi(1) # returns 0.0 or 4.0
1 <= darts <= 100,000Use the random module's shared functions and do not call random.seed: the tests seed it themselves, then check that the estimate is close to pi, never one exact value.
First solves only, ranked by stars and then time.