How to Generate Random Number Based on Probability in Java
java, sampling
Solution
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.
Problem
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