Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

Thread: Random 0/1 with given possibility

1. 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.

3. 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.

4. Re: Random 0/1 with given possibility

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?

5. 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.

6. The Following User Says Thank You to copeg For This Useful Post:

juwan (November 11th, 2010)

7. Re: Random 0/1 with given possibility

I've solved my problem:

p = 0,7 (user input)

int random1 = (double) (Math.random());
int win = 0;
if(random1 < p){
win = 1;
}

8. Re: Random 0/1 with given possibility

```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