Use probability to approach Pi

Once I found this interview question: calculate Pi. Where, all of us have learned calculating Pi in our primary math class by using regular polygon to approach a circle.

Today I am gonna show you a probability way.


Check the following graph. I hope it is self-explainatory.


class Pi{ 
        public static void main(String[] args){
                if(args.length < 1)
                long iter = Long.parseLong(args[0]);
                double pi = calculate(iter);
                System.out.println(String.format("after %d iterations, pi is %f", iter, pi ));  
        public static double calculate(long simNum){
                long i =0L;
                long count =0L;
                        double x = Math.random();
                        double y = Math.random();
                        double result = x*x+y*y;
                        if(result < 1.0D){
                return 4.0D* count/simNum;


lucas@lucas-ubuntu:~/dev/workspace/pi$ java Pi 1000
after 1000 iterations, pi is 3.032000
lucas@lucas-ubuntu:~/dev/workspace/pi$ java Pi 10000
after 10000 iterations, pi is 3.137200
lucas@lucas-ubuntu:~/dev/workspace/pi$ java Pi 100000
after 100000 iterations, pi is 3.140240
lucas@lucas-ubuntu:~/dev/workspace/pi$ java Pi 1000000
after 1000000 iterations, pi is 3.144108
lucas@lucas-ubuntu:~/dev/workspace/pi$ java Pi 10000000
after 10000000 iterations, pi is 3.141199
lucas@lucas-ubuntu:~/dev/workspace/pi$ java Pi 100000000
after 100000000 iterations, pi is 3.141486


When iteration is set to 100,000,000, it takes about half a minute on my i7 Core Mac Pro with precision only to 3 digits.