特定範圍內的偽隨機數

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 值的一半時,這種效能降低將變得更加明顯。