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:

  1. why treat case n power of 2 specially ? performance ?
  2. why doest reject numbers bits - val + (n-1) < 0 ?

next generates random bits.

  1. 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.

  2. when n isn't power of 2, throws away numbers @ "top" of range random number evenly distributed. e.g. imagine had n=3, , imagine using 3 bits rather 31 bits. bits randomly generated number between 0 , 7. how can generate fair random number there? answer: if bits 6 or 7, throw away , generate new one.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -