Implementation of java.util.Random.nextInt -
this function java.util.random
. returns pseudorandom int
uniformly distributed between 0
, given n
. unfortunately did not it.
public int nextint(int n) { if (n <= 0) throw new illegalargumentexception("n must positive"); if ((n & -n) == n) // i.e., n power of 2 return (int)((n * (long)next(31)) >> 31); int bits, val; { bits = next(31); val = bits % n; } while (bits - val + (n-1) < 0); return val; }
my questions are:
- why treat case
n
power of 2 specially ? performance ? - why doest reject numbers
bits - val + (n-1) < 0
?
next
generates random bits.
when
n
power of 2, random integer in range can generated generating random bits (i assume generating 31 , throwing away reproducibility). code path simpler , guess it's more commonly used case it's worth making special "fast path" case.when
n
isn't power of 2, throws away numbers @ "top" of range random number evenly distributed. e.g. imagine hadn=3
, , imagine using 3 bits rather 31 bits.bits
randomly generated number between 0 , 7. how can generate fair random number there? answer: ifbits
6 or 7, throw away , generate new one.
Comments
Post a Comment