Michael
Michael

Reputation: 343

Java Random.nextInt() behavior

I wrote this simple code just out of curiosity and encountered some behavior of the nextInt() method from the Java Random class that I don't quite understand. Can anyone help me to figure it out?

The program simulates a simple coin flipping. So as far as I understand the probability of the nextInt(101) for numbers less and greater than 49 should be equal.

But as long as I increase the number of iterations, the balance tends to get positive, for example after 100,000 iterations, I didn't get a negative number. Why does this happen?

public static void main(String[] args) {
    int balance = 0;

    for (int i = 0; i < 100000; i++) {

        Random random = new Random();
        int result = random.nextInt(101);

        if (result > 49) {
            balance++;
        } else {
            balance--;
        }
    }

    System.out.println("Player's balance = " + balance);
}

Upvotes: 0

Views: 4900

Answers (3)

WJS
WJS

Reputation: 40024

you are testing 51 possibilities for a positive outcome and only 50 possibilities for a negative outcome.

  • 100-50 = 51 possibilities
  • 0-49 = 50 possibilities.

Upvotes: 1

Khaja Md Sher E Alam
Khaja Md Sher E Alam

Reputation: 906

If you have tried, random.nextInt(99), result will be different, I got minus value many times.

The reason behind this is that random.nextInt() Method. quoted from the JavaDoc.

 The algorithm is slightly tricky.  It rejects values that would result
 in an uneven distribution (due to the fact that 2^31 is not divisible
 by n). The probability of a value being rejected depends on n.  The
 worst case is n=2^30+1, for which the probability of a reject is 1/2,
 and the expected number of iterations before the loop terminates is 2.

Please see here Random.java#nextInt(int)

Upvotes: -2

Michael Kreutz
Michael Kreutz

Reputation: 1256

You call int result = random.nextInt(101) which creates uniformly distributed integers in [0,100], which can take 101 different values. If you check if (result > 49) then you have 51 possible values ([50,100]) and in the else case you have only 50 values ([0,49]). Thus the result is more likely to be in the upper part. To fix it you can do int result = random.nextInt(100).

Upvotes: 6

Related Questions