Probability in Java

Jeel Shah picture Jeel Shah · Nov 18, 2011 · Viewed 64.9k times · Source

I was curious to know, how do I implement probability in Java? For example, if the chances of a variable showing is 1/25, then how would I implement that? Or any other probability? Please point me in the general direction.

Answer

Michael Berry picture Michael Berry · Nov 18, 2011

You'd use Random to generate a random number, then test it against a literal to match the probability you're trying to achieve.

So given:

boolean val = new Random().nextInt(25)==0;

val will have a 1/25 probability of being true (since nextInt() has an even probability of returning any number starting at 0 and up to, but not including, 25.)

You would of course have to import java.util.Random; as well.

As pointed out below, if you're getting more than one random number it'd be more efficient to reuse the Random object rather than recreating it all the time:

Random rand = new Random();
boolean val = rand.nextInt(25)==0;

..

boolean val2 = rand.nextInt(25)==0;