Java:0 <= x < n 范围内的随机长数

标签 java random range long-integer

Random 类有一个方法可以在给定范围内生成随机 int。例如:

Random r = new Random(); 
int x = r.nextInt(100);

这将生成一个大于或等于 0 且小于 100 的 int 数字。我想对 long 数字执行完全相同的操作。

long y = magicRandomLongGenerator(100);

Random 类只有 nextLong(),但不允许设置范围。

最佳答案

Java 7(或Android API Level 21 = 5.0+)开始,您可以直接使用ThreadLocalRandom.current().nextLong(n)(对于0 ≤ x < n) 和 ThreadLocalRandom.current().nextLong(m, n) (对于 m ≤ x < n)。请参阅@Alex详细回答。

<小时/>

如果您无法使用Java 6(或Android 4.x),则需要使用外部库(例如org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator( ).nextLong(0, n-1),请参阅 @mawaldne 的答案),或实现您自己的 nextLong(n)

根据Random documentation , nextInt 实现为

 public int nextInt(int bound) {
   if (bound <= 0)
     throw new IllegalArgumentException("bound must be positive");

   if ((bound & -bound) == bound)  // i.e., bound is a power of 2
     return (int)((bound * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % bound;
   } while (bits - val + (bound-1) < 0);
   return val;
 }

因此我们可以修改它来执行nextLong:

long nextLong(Random rng, long bound) {
    // error checking and 2^x checking removed for simplicity.
    long bits, val;
    do {
        bits = (rng.nextLong() << 1) >>> 1;
        val = bits % bound;
    } while (bits-val+(bound-1) < 0L);
    return val;
}

关于Java:0 <= x < n 范围内的随机长数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564561/

相关文章:

arrays - 如何在 Ruby 中将整数数组压缩为范围和整数数组

java - 使用循环在 JSF 中创建命令按钮?

c++ - 如何简洁、便携、彻底地播种mt19937 PRNG?

python - sklearn 的 ParameterSampler 中的 random_state 参数有什么作用?

database - swift 。如何从 Firebase 数据库中选择一个随机用户?

math - 一维线段/范围相交测试 : Solution Name?

range - 检查数字是否在 free pascal 的范围内

java - 字符串中的数字

java - 在 Java 9 中创建模块项目时出现问题

java - 如何仅在给定已实现的方法的情况下创建队列?