Calculating Pi – Monte Carlo method

Monte Carlo methods are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical result. Wikipedia link.
Using Monte Carlo method Pi is calculated by
1. Drawing a square on the ground, then inscribe a circle within it.
2. Uniformly scatter some objects of uniform size (grains of rice or sand) over the square.
3. Count the number of objects inside the circle and the total number of objects.
4. The ratio of the two counts is an estimate of the ratio of the two areas, which is pi/4. Multiply the result by 4 to estimate pi.
Monte Carlo pi

if the radius of the circle is 1 then any point inside the circle is x^2+y^2<=1 (standard equation of circle x^2+y^2=r^2)
Code Download link

public class Calcpi {
public static void main(String[] args) {
double x, y;
int insideCircle = 0, total = 999999;//Integer.MAX_VALUE; //MAX_VALUE will need a lots of time but will yeild better result
for (int i = 0; i < total; i++) {
x = Math.random();
y = Math.random();
if (x * x + y * y <= 1){
System.out.print("Calculating pi "+Math.round((100.0*i)/total)+"%\r");
System.out.println("\n"+(4.0 * insideCircle / total)+" as i calculated");
System.out.println(Math.PI+" as the system uses");

Use Integer.MAX_VALUE to calculate up to maximum possible signed integer on normal java programming. It will take longer time than using 999999. Change this value to test with higher and lower approximation.


Incoming search terms:

  • Estimating pi by Monte Carlo java
  • tushar roy data algorithm
  • tushar roy wiki

Tushar Roy

Software Engineer (Backend engineer), Android Developer,

Leave a Reply

Your email address will not be published. Required fields are marked *