Java:0

编程入门 行业动态 更新时间:2024-10-26 16:21:24
Java:0 <= x

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

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

这将产生一个大于等于0且小于100的int数。我想用长数字做完全相同的操作。

long y = magicRandomLongGenerator(100);

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

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

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

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 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<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) 。

根据http://java.sun.com/j2se/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 :

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; }

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.


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).

According to http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html nextInt is implemented as

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; }

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; }

更多推荐

本文发布于:2023-08-06 18:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454937.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!