Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java生成30到32位之间的随机数_Java - Fatal编程技术网

java生成30到32位之间的随机数

java生成30到32位之间的随机数,java,Java,在阅读其他文章时,我想我必须使用BigInteger生成20000个介于30到32位之间的随机数 public BigInteger(int numBits, Random rnd) 但这不允许数字的最小和最大范围 谢谢如果您想使用此功能,您可以 public static BigInteger random(Random rand, BigInteger minValue, BigInteger maxValue) { BigInteger range = maxValue.subt

在阅读其他文章时,我想我必须使用BigInteger生成20000个介于30到32位之间的随机数

public BigInteger(int numBits, Random rnd)
但这不允许数字的最小和最大范围


谢谢

如果您想使用此功能,您可以

public static BigInteger random(Random rand, BigInteger minValue, BigInteger maxValue) {
    BigInteger range = maxValue.subtract(minValue).add(BigInteger.ONE);
    int bits = range.bitLength();
    BigInteger ret;
    do {
        ret = new BigInteger(bits, rand);
    } while(ret.compareTo(range) >= 0);
    return ret.add(minValue);
}

一个简单的解决方案是在
30
31
之间随机选择,和
32
每次您要生成一个数字。20000个数字必须是唯一的吗?@HunterMcMillen您必须使用加权随机数:31位数字的数量是30位数字的10倍。传递
random
实例的目的是什么?为什么这是一个要求?那么
numBits
的含义是什么呢?是的,20000个数字必须是唯一的,只是想知道是否不是循环
ret.mod(range).add(minValue)
会比可能对RNG进行多个调用更好的性能。如果生成更多的位,这样结果就不会扭曲,这是可能的(所以每个数字都有一个合理的平等机会)你必须对它进行基准测试,看看哪个更快。