Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
Dan Avatar asked Apr 06 '15 16:04

Dan


People also ask

How do you randomize true or false in Java?

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.

What is a random Boolean?

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.

How do you generate a random Boolean in C++?

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);


1 Answers

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.

like image 93
Bobulous Avatar answered Oct 11 '22 04:10

Bobulous