Generating a number between 1 and 2 java Math.random()
This question already has an answer here:
If you want the values 1 or 2 with equal probability, then int temp = (Math.random() <= 0.5) ? 1 : 2; int temp = (Math.random() <= 0.5) ? 1 : 2; is all you need. That gives you a 1 or a 2, each with probability 1/2.
int tmp = (int) ( Math.random() * 2 + 1); // will return either 1 or 2
Math.random() returns numbers from [0, 1) . Because (int) always rounds down (floors), you actually want the range [1,3) , so that [1,2) will be rounded to 1 and [2,3) will be rounded to 2.
Try this.
int tmp = (int)( Math.floor( Math.random() + 1.5 ) )
Math.random() -> [0, 1)
Math.random() + 1.5 -> [1.5, 2.5)
So when you take the floor, it is either 1 or 2 with equal
probability because [1.5, 2.5) = [1.5, 2) U [2, 2.5)
and length([1.5, 2)) = length([2, 2.5)) = 0.5 .
上一篇: 在两者之间生成随机Double
