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?
In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.
The nextBoolean() method of the Random class is an instance method that generates pseudorandom, uniformly distributed Boolean values. True and false values are generated with approximately equal probability.
Until now I used the following code to generate a random bool : bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);
The reason is found in the API for the setSeed
method:
The implementation of setSeed by class Random happens to use only 48 bits of the given seed.
In fact the long
you provide as the seed value is multiplied by a fixed value (defined privately in the Random
class) and then only the least significant 48 bits are considered. Even though this multiplier is large, because your sequence of i
values are all consecutive they all produce seed values which are numerically similar. So the first few thousand values are effectively seen as having the same value to the nextBoolean
method, and you get the exact same initial boolean value. Calling nextBoolean
again (without calling setSeed
again) will remultiply the seed value, so you quickly move away from seeing the same pattern.
If you do call the setSeed
method you should only need to call it once, and you should do so outside of the loop. But the Random
class is entirely capable of choosing its own seed value, so I recommend that you do not call setSeed
at all unless you know why you're doing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With