Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate Random Number Based on Probability in Java

Tags:

java

sampling

I want to randomly select a '1' 10% of the time, a '2' 30% of the time and a '3' the other 60% of a time. I am wondering if there is a method that allows me to randomly sample based on these probabilities in Java.

Thank you

like image 607
Chloee Robertson Avatar asked Oct 15 '25 19:10

Chloee Robertson


2 Answers

First generate a double that's uniformly distributed between 0.0 and 1.0. Then split the range (0.0 < x < 1.0) into subranges that correspond to your desired probabilities:

  • 0.0 <= x < 0.1 becomes 1 (interval width is (0.1 - 0.0) = 0.1, or 10%);
  • 0.1 <= x < 0.4 becomes 2 (interval width is (0.4 - 0.1) = 0.3, or 30%);
  • 0.4 <= x < 1.0 becomes 3 (interval width is (1.0 - 0.4) = 0.6, or 60%).

In code:

double rand = rng.nextDouble();
if (rand < .1) {
  return 1;
} else if (rand < .1 + .3) {
  return 2;
} else {
  return 3;
}

(where rng is an instance of java.util.Random.)

This method can be easily generalised to an arbitrary set of target probabilities.

like image 107
NPE Avatar answered Oct 18 '25 07:10

NPE


This approach is applicable in every language. Just get a big random number, then take a mod of some number, and check for ranges.

Random rand = new Random();
int r = rand.nextInt(10000000);
int m = r % 10;
if (m < 1) return 1; // 10 %
else if (m < 4) return 2; // 30 %
else return 3; // 60 %
like image 38
Rustam Ibragimov Avatar answered Oct 18 '25 08:10

Rustam Ibragimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!