I'm trying to get a random value of 0 or 1, with given probability (like 0,7) of it being 1.
Which function can I use in such a case?
Where can I find that function better explained?
Any help would be very apriciated.
Printable View
I'm trying to get a random value of 0 or 1, with given probability (like 0,7) of it being 1.
Which function can I use in such a case?
Where can I find that function better explained?
Any help would be very apriciated.
I look over util.random and math.random, but I was't able to find anything, that would allow me to set the probability.
I don't believe there is a function or utility (that I know of) which allows you to alter the probability distribution of the random output. To do so manually could get tricky but in this case is relatively easy. Get a random fraction value (using Random class posted above), skew this value by adding the appropriate probability distribution value, and cast this to an integer.
I've solved my problem:
p = 0,7 (user input)
Quote:
int random1 = (double) (Math.random());
int win = 0;
if(random1 < p){
win = 1;
}
dbCode :int totalOnes = 0; double iterations = 100000000; Random random = new Random(); for (int i = 0; i < iterations; i++) { int zeroOrOneWithPointSevenProbabilityOfOne = random.nextInt(10) < 3 ? 0 : 1; if (zeroOrOneWithPointSevenProbabilityOfOne == 1) totalOnes++; } System.out.println(totalOnes + " (" + totalOnes / iterations + ")");