特定范围内的伪随机数

Random 的方法 nextInt(int bound) 接受上限专有边界,即返回的随机值必须小于的数字。但是,只有 nextInt 方法接受一个绑定; nextLongnextDouble 等没有。

Random random = new Random();
random.nextInt(1000); // 0 - 999

int number = 10 + random.nextInt(100); // number is in the range of 10 to 109

从 Java 1.7 开始,你也可以使用 ThreadLocalRandomsource )。此类提供线程安全的 PRNG(伪随机数生成器)。请注意,此类的 nextInt 方法同时接受上限和下限。

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
ThreadLocalRandom.current().nextInt(min, max + 1);

请注意,官方文档指出,当 bound 接近 2 30 +1 时,nextInt(int bound) 可以做奇怪的事情 (强调添加):

该算法有点棘手。它拒绝会导致分布不均匀的值 (由于 2 ^ 31 不能被 n 整除)。值被拒绝的概率取决于 n。最坏的情况是 n = 2 ^ 30 + 1,其中拒绝的概率是 1/2,并且循环终止之前的预期迭代次数是 2。

换句话说,指定一个约束将(略微)降低 nextInt 方法的性能,并且当 bound 接近 max int 值的一半时,这种性能降低将变得更加明显。