K. Day - 5 months ago 53

Java Question

I want to know how I can use 2 same numbers in a random on Java, I mean, I want to get 5% do something and another 5% do another thing, but in the same random (

`double d = Math.random()`

I wanted to get two values with the same numbers in a Java Random, so I can do that when that random is 5% something happens, but if that get another 5% another thing will happen.

Answer

```
Random r = new Random();
double roll = r.nextDouble();
if (roll < 0.05)
// 5% chance to do something
else if (roll < 0.10)
// 5% chance to do something else
```

Explanation: The roll above is uniformly distributed between 0 and 1, which implies that the probability that it will be in an interval of length 0.05 is 5%. So to answer the follow up question in the comment, yes: you could extend this by checking if roll < 0.15 as well. Note however that due to the way the else if works, the order is important.

Also note that the two events are not independent, as if one occurs, the other will not, and vice versa. If you want independence, you need to roll several times.