Random int function behavior in Java

I have the following 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 close to 666666 This means that two thirds of the resulting number is lower than the lower half of n Not when n = 2 / 3 * integer MAX_ Value to obtain this value 4 / 7 is another score that gives me a similar difference (~ 5714285) However, if n = integer MAX_ Value or n = integer MAX_ Value / 2, a uniform distribution is obtained How does this behavior differ from the scores used Someone can know something about it

PS: I got this question from Joshua Bloch's book "effective Java"

Solution

The problem lies in the modulus (%) operator, resulting in uneven distribution of numbers

For example, suppose max_ Int is 10, and N = 7, the mod operator maps the values 8, 9, and 10 to 1, 2, and 3, respectively This will result in numbers 1, 2 and 3 being twice as likely as all other numbers

One way to solve this problem is to check RND The output of nextint() and try again when it is greater than n

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>