# Random 0/1 with given possibility

• November 10th, 2010, 09:16 AM
juwan
Random 0/1 with given probability
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.
• November 10th, 2010, 09:25 AM
helloworld922
Re: Random 0/1 with given possibility
• November 10th, 2010, 10:12 AM
juwan
Re: Random 0/1 with given possibility
I look over util.random and math.random, but I was't able to find anything, that would allow me to set the probability.
• November 10th, 2010, 10:47 AM
KevinWorkman
Re: Random 0/1 with given possibility
Quote:

Originally Posted by juwan
I look over util.random and math.random, but I was't able to find anything, that would allow me to set the probability.

Say you have a 6-sided die, and you wanted to use it to decide something with a 5/6 chance of happening in one roll. What would you do?
• November 10th, 2010, 12:34 PM
copeg
Re: Random 0/1 with given possibility
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.
• November 11th, 2010, 01:29 PM
juwan
Re: Random 0/1 with given possibility
I've solved my problem:

p = 0,7 (user input)

Quote:

int random1 = (double) (Math.random());
int win = 0;
if(random1 < p){
win = 1;
}
• November 12th, 2010, 04:30 AM
Darryl.Burke
Re: Random 0/1 with given possibility
Code :

```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 + ")");```
db