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
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:
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.
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 %
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With