Java:0 <= x <中的随机长数范围 [英] Java: random long number in 0 &lt;= x &lt; n range

查看:22
本文介绍了Java:0 <= x <中的随机长数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Random 类具有在给定范围内生成随机 int 的方法.例如:

Random class has a method to generate random int in a given range. For example:

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

这将生成一个大于或等于 0 且小于 100 的 int 数.我想对长数做完全相同的事情.

This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number.

long y = magicRandomLongGenerator(100);

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

Random class has only nextLong(), but it doesn't allow to set range.

推荐答案

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

Starting from Java 7 (or Android API Level 21 = 5.0+) you could directly use ThreadLocalRandom.current().nextLong(n) (for 0 ≤ x < n) and ThreadLocalRandom.current().nextLong(m, n) (for m ≤ x < n). See @Alex's answer for detail.

如果您坚持使用 Java 6(或 Android 4.x),您需要使用外部库(例如 org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1),参见 @mawaldne 的回答),或者实现你的自己的nextLong(n).

If you are stuck with Java 6 (or Android 4.x) you need to use an external library (e.g. org.apache.commons.math3.random.RandomDataGenerator.getRandomGenerator().nextLong(0, n-1), see @mawaldne's answer), or implement your own nextLong(n).

根据 https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Random.html nextInt 实现为

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

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

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

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

So we may modify this to perform nextLong:

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

这篇关于Java:0 <= x <中的随机长数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆