简体   繁体   English

生成15位随机数时,后3位始终为零

[英]Last 3 digits always zero when generating 15-digit random number

I wanted to generate a random number between 1_000_0000_0000_000 and 9_999_9999_9999_999L using Java so I used the following code, 我想使用Java生成一个介于1_000_0000_0000_0009_999_9999_9999_999L之间的随机数,因此我使用了以下代码,

final long MAX_NUMBER = 9_999_9999_9999_999L;
final long MIN_NUMBER = 1_000_0000_0000_000L;
System.out.print(Long.valueOf(new Random().nextLong() * 
                     (MAX_NUMBER - MIN_NUMBER)));

The problem with the code is, the code does generate 15 digit random number, but the last 3-digits are always zero, and some time it generates negative number. 代码的问题在于,代码确实会生成15位数字的随机数,但最后3位数字始终为零,有时还会生成负数。

Can anybody tell me why the last 3-digits are always zero ? 谁能告诉我为什么最后三位数字总是为零?

Here are some of the outputs, 这是一些输出,

7160629848698886104000

-6581075034034719564000

6645937379553681443000

6363833355925386903000

nextLong() may return any long value, which include negative values. nextLong()可以返回任何长值,包括负值。 Multiplying the result of nextLong() by (MAX_NUMBER - MIN_NUMBER) may cause an overflow and will not give you a result in the required range. nextLong()的结果乘以(MAX_NUMBER - MIN_NUMBER)可能会导致溢出,并且不会为您提供所需范围内的结果。

You can use Math.random() instead : 您可以改用Math.random()

System.out.print((long)(Math.random() * (MAX_NUMBER - MIN_NUMBER))+ MIN_NUMBER);

Strange, I cannot reproduce your problem. 奇怪,我无法重现您的问题。 Looks like the JVM's random number generation is flawed? 看起来JVM的随机数生成有缺陷吗? You can try SecureRandom instead of Random. 您可以尝试使用SecureRandom代替Random。

By the way, I just wanted to note that the Math.random() * (max - min) + min pattern does not result in uniform distributed (though it comes close). 顺便说一句,我只想指出Math.random() * (max - min) + min模式不会导致均匀分布(尽管它很接近)。

You can try out Apache Commons: RandomDataGenerator . 您可以尝试使用Apache Commons: RandomDataGenerator It has an nextLong(long lower, long upper) implementation. 它具有nextLong(long lower, long upper)实现。

https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/random/RandomDataGenerator.html https://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/random/RandomDataGenerator.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM