Generating values for random variables with a certain distribution usually works like this:
- You have a function which generates a random
0 <= q < 1
,
- You apply the quantile function and you obtain the value of your variable.
In your case you have a discrete random variable. You need an instance of Random
:
private static final Random random = new Random();
the values assumed by the variable:
private static final double[] values = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Compute the cumulative distribution function (sum of probabilities of the values up to the specific value) for these values:
private static final double[] cdf = {1.0 / 9, 2.0 / 9, 3.0 / 9, 4.0 / 9, 5.0 / 9, 1.0};
You random generating function will return the last value for which the cdf is not greater than q
:
public static double randomValue() {
double q = random.nextDouble();
for (int i = 0; i < values.length; i++) {
if (q > cdf[i]) continue;
return values[i];
}
throw new IllegalStateException();
}