In the example Josh gives of the flawed random method that generates a positive random number with a given upper bound n
, I don't understand the two of the flaws he states.
The method from the book is:
private static final Random rnd = new Random();
//Common but deeply flawed
static int random(int n) {
return Math.abs(rnd.nextInt()) % n;
}
- He says that if n is a small power of 2, the sequence of random numbers that are generated will repeat itself after a short period of time. Why is this the case? The documentation for
Random.nextInt()
saysReturns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.
So shouldn't it be that if n is a small integer then the sequence will repeat itself, why does this only apply to powers of 2? - Next he says that if n is not a power of 2, some numbers will be returned on average more frequently than others. Why does this occur, if
Random.nextInt()
generates random integers that are uniformly distributed? (He provides a code snippet which clearly demonstrates this but I don't understand why this is the case, and how this is related to n being a power of 2).