Friday, March 24, 2023

Estimate π by counting random numbers

So I was given a quiz: to estimate π by counting random numbers. This is known as the Monte Carlo method. Take random number x and y from 0..1, it can be inside or outside of a quarter circle. To estimate pi, just count how many dots are in.

First I was kinda totally shocked by this method.. haven't heard of this before. The quiz was not formulated in a very clear way so I basically had no idea how to proceed. This is actually quite simple that high school kids should be able to do with a little python method or whatever language. Here is mine in Java:

	public double estimatePi() {
		int count=0;
		int MAX=100000;
		for (int i=0; i < MAX; i++) {
			double x = Math.random();
			double y = Math.random();
			if (Math.sqrt(x*x+y*y)<1) {
				count++;
			}
		}
		return count*4/(MAX*1.0);
	}
It gets pretty close to 3.14.

Although computers nowadays are pretty fast, but it is expensive (as in time consuming) operation to do square root, and lots of it to get a fair estimate. Math.PI gives you a lot of digits, millions of digits of π are now known there is no more need to estimate it. But nevertheless it is good little math and computer exercise. I lived in darkness because never heard of this method before.

No comments: