You Can Calculate Pi with Random Numbers and Python

Rhett Allain
9 min readMar 2, 2024
Photo: Rhett Allain. Illustration of the Monte Carlo method for calculating Pi.

Pi is a magical number. There’s no doubt about that. The two coolest things for me are that it’s irrational (goes on forever) and that it shows up in a bunch of weird places in physics (here’s the explanation of why).

Pretty much everyone knows the first few digits of Pi — like 3.1415 (maybe you even know more). But how do we find these values? We could use the most fundamental definition of Pi, the ratio of circumference (C ) to diameter (D) for circular objects:

But that’s not much fun, is it? We can actually determine Pi with random numbers. In fact, one of the earlier methods did exactly that. The famous Buffon’s needle problem drops equal length sticks (or needles) randomly on the floor. Then, by counting how many needles cross parallel lines you can get an estimate for Pi. It’s a really cool problem, but sort of difficult to see how you get Pi (but not impossibly difficult).

Let’s use a different method with random numbers. Let me explain the idea first and then I’ll go over ALL the details you need to build this in python.

Monte Carlo Pi

Whenever we solve a physics problem with random numbers, we call this a Monte Carlo method. Yes, this is named after the casinos in Monte Carlo since it involves the idea of chance.

--

--

Rhett Allain

Physics faculty, science blogger of all things geek. Technical Consultant for CBS MacGyver and MythBusters. WIRED blogger.