如何在特定范围内生成随机int值?
以下方法存在与整数溢出相关的错误:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
我的一个朋友今天在大学里问过我同样的问题(他的要求是生成一个介于1和-1之间的随机数)。所以我写了这个,到目前为止,它在我的测试中运行良好。理想情况下,有很多方法可以在给定范围内生成随机数。试试看:
功能:
private static float getRandomNumberBetween(float numberOne, float numberTwo) throws Exception{
if (numberOne == numberTwo){
throw new Exception("Both the numbers can not be equal");
}
float rand = (float) Math.random();
float highRange = Math.max(numberOne, numberTwo);
float lowRange = Math.min(numberOne, numberTwo);
float lowRand = (float) Math.floor(rand-1);
float highRand = (float) Math.ceil(rand+1);
float genRand = (highRange-lowRange)*((rand-lowRand)/(highRand-lowRand))+lowRange;
return genRand;
}
执行方式如下:
System.out.println( getRandomNumberBetween(1,-1));
请原谅我过于挑剔,但大多数人建议的解决方案,即min+rng.nextInt(max-min+1),似乎很危险,因为:
rng.nextInt(n)无法达到整数.MAX_VALUE。当min为负值时,(max-min)可能会导致溢出。
万无一失的解决方案将为[Integer.min_VALUE,Integer.max_VALUE]内的任何min<=max返回正确的结果。请考虑以下简单的实现:
int nextIntInRange(int min, int max, Random rng) {
if (min > max) {
throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
}
int diff = max - min;
if (diff >= 0 && diff != Integer.MAX_VALUE) {
return (min + rng.nextInt(diff + 1));
}
int i;
do {
i = rng.nextInt();
} while (i < min || i > max);
return i;
}
尽管效率低下,但请注意while循环中成功的概率始终为50%或更高。
下面是一个简单的示例,它显示了如何从闭合的[min,max]范围生成随机数,而min<=max为真
您可以将其作为孔中字段类重用,也可以将所有Random.class方法放在一个位置
结果示例:
RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert
来源:
import junit.framework.Assert;
import java.util.Random;
public class RandomUtils extends Random {
/**
* @param min generated value. Can't be > then max
* @param max generated value
* @return values in closed range [min, max].
*/
public int nextInt(int min, int max) {
Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
if (min == max) {
return max;
}
return nextInt(max - min + 1) + min;
}
}