mercredi 24 décembre 2014

Random int function behavior in Java

I have the following piece of code:



public class Main {
private static final Random rnd = new Random();

private static int getRand(int n) {
return (Math.abs(rnd.nextInt())%n);
}

public static void main(String[] args) {
int count=0, n = 2 * (Integer.MAX_VALUE/3);
for(int i=0; i<1000000; i++) {
if(getRand(n) < n/2) {
count++;
}
}
System.out.print(count);
}
}


This always gives me a number closer to 666,666. Meaning two-thirds of the numbers generated are below the lower half of n. Not that this is obtained when n = 2/3 * Integer.MAX_VALUE. 4/7 is another fraction that gives me a similar spread (~5714285). However, I get an even spread if n = Integer.MAX_VALUE or if n = Integer.MAX_VALUE/2. How does this behavior differ with the fraction used. Can somebody throw some light on it.


PS: I got this problem from the book Effective Java by Joshua Bloch.





Aucun commentaire:

Enregistrer un commentaire