Search code examples
javapi

Wrong output in pi value using monte carlo method


I tried making a JAVA program to compute value of pi using monte carlo method(without using any visualizaton) everything seems fine to me but whenever I run it, the answer is always 0.0 . Cannnot figure out, what is wrong please help.

This is the code:

    import java.util.*;

    // Compiler version JDK 11.0.2

    class PiMonteCarlo{
        public static void main(String args[]){ 
            Random rand =new Random();
            double r=1.0;
            int cir=0,sq=0,range=200+1,min=0;
            for(int i=1;i<=200000;i++){
                double y = rand.nextDouble();
                double x = rand.nextDouble();
                double d=(x*x)+(y*y);
                if(d<=r){
                    cir++;
                }
            sq++;
            }
            double rat=cir/sq;
            System.out.print(4*rat);
        }
    }

Solution

  • Welcome to stackoverflow.

    The thing is, you need a lot of iterations to have a good estimation of pi.

    Instead of 4 use 4.0 to make a double division.

    import java.util.*;
    
    class PiMonteCarlo{
        public static void main(String args[]){
            double radius = 1;
            Random random = new Random();
            int inside = 0;
            int trials = 10^100000000;
            for(int i = 1; i<=trials; i++){
                double y = random.nextDouble();
                double x = random.nextDouble();
                if((x*x)+(y*y) <= radius){
                    inside++;
                }
            }
            double rat = 4.0 * inside/trials;
            System.out.print(rat);
        }
    }