Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Random Class not truly random?

Tags:

java

random

I am trying to simulate the math puzzle I found on http://blog.xkcd.com/2010/02/09/math-puzzle/. However, the java random class is returning weird results. In the code below, the result is what is expected. The output is somewhere around .612 for the first line and between .49 and .51 for the second. int trials = 10000000; int success = 0;

    int returnstrue = 0;

    for (int i = 0; i < trials; i++) {
        Random r = new Random();
        //double one = r.nextDouble()*10000;
        //double two = r.nextDouble()*10000;
        double one = 1;
        double two = Math.PI;


        double check = r.nextDouble();
        boolean a = r.nextBoolean();


        if(a)
        {
            returnstrue++;
        }
        if(a){
            if((check>p(one)) && two > one)
            {
                success++;
            }
            if((check<p(one))&& two<one)
            {
                success++;
            } 
        }
        else{
            if((check>p(two)) && two < one)
            {
                success++;
            }
            if((check<p(two))&& two>one)
            {
                success++;
            }      
        }
    }
    System.out.println(success/(double)trials);
    System.out.println(returnstrue/(double)trials);

However, when I switch the lines of

 double check = r.nextDouble();
 boolean a = r.nextBoolean();

to

  boolean a = r.nextBoolean();
  double check = r.nextDouble();

the output is around .476 for the first number and .710 for the second. This implies that the nextBoolean() method is returning true 70% of the time in the later configuration. Am I doing something wrong or is this just a bug?

like image 763
starwing123 Avatar asked Dec 11 '22 20:12

starwing123


1 Answers

Move the instantiation of r to outside the for loop, as in:

Random r = new Random();
for (int i = 0; i < trials; i++) {
    :
}

What you are doing now is creating a new one every time the loop iterates and, since the seed is based on the time (milliseconds), you're likely to get quite a few with the same seed.

That's almost certainly what's skewing your results.

So, yes, it is a bug, just in your code rather than in Java. That tends to be the case in about 99.9999% of the times when people ask that question since Java itself is continuously being tested by millions around the world and that snippet of yours has been tested by, well, just you :-)

like image 54
paxdiablo Avatar answered Dec 14 '22 09:12

paxdiablo