lundi 6 avril 2015

Random.nextBoolean() Always Returns True No Matter the Seed

When I run the following code, no matter what range I use for the for loop, the code always prints out true ten times.



public static void main(String[] args)
{
Random bool = new Random();

for (int i = 0; i < 10; i++) {
bool.setSeed(i);
System.out.println(bool.nextBoolean());
}
}


However, if I make a slight change to the code and let the random generator run the nextBoolean() function once before printing, I get a normal distribution of true and false in the output that chages when I change the range of the for loop:



public static void main(String[] args)
{
Random bool = new Random();

for (int i = 0; i < 10; i++) {
bool.setSeed(i);
bool.nextBoolean(); //Only change
System.out.println(bool.nextBoolean());
}
}


It seems to me that the nextBoolean() function always returns true when executed the first time, is there any reason for this behavior?





Aucun commentaire:

Enregistrer un commentaire