Java Random Class is not really random?

I am trying to simulate a math puzzle that I found at http://blog.xkcd.com/2010/02/09/math-puzzle/ . However, the random java class returns strange results. In the code below, the result is what is expected. The output is somewhere around 0.612 for the first line and between 0.49 and 0.51 for the second. int trial = 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

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

to

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

the output is about 0.766 for the first number and 0.710 for the second. This means that the nextBoolean () method returns 70% of the time in a later configuration. Am I doing something wrong or is it just a mistake?

+4
source share
1 answer

Move instance r outside the for loop, as shown in the figure:

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

Now you create a new one every time the cycle repeats, and since the seed is based on time (milliseconds), you are likely to get a lot with the same seed.

This is almost certainly what distorts your results.

So, yes, this is a mistake, just in your code, and not in Java. This occurs in approximately 99.9999% of cases when people ask this question, because Java itself is constantly tested by millions of people around the world, and this fragment has been tested, well, only you :-)

+12
source

Source: https://habr.com/ru/post/1448028/


All Articles