简体   繁体   中英

Safely generate random numbers between some range in Java

How do I safely generate a random integer value in a specific range?

I know many people have asked this before, this post for example, but the method doesn't seem to be safe. Let me explain:

The 'Math' library has Math.random() which generates a random value in the range [0, 1). Using that, one can construct an algorithm like

int randomInteger = Math.floor(Math.random() * (Integer.MAX_VALUE - Integer.MIN_VALUE + 1) + Integer.MIN_VALUE)

to generate a random number between Integer.MAX_VALUE and Integer.MIN_VALUE . However, Integer.MAX_VALUE - Integer.MIN_VALUE will overflow.

The goal is not to merely generate random numbers but to generate them evenly, meaning 1 has the same probability to appear as Integer.MAX_VALUE . I know there are work-arounds to this, such as casting large values to long but then the problem again is how to generate a long integer value from Long.MIN_VALUE to Long.MAX_VALUE .

I'm also not sure about other pre-written algorithms as they can overflow too and cause the probability distribution to change. So my question is whether there is a mathematical equation that uses only integers (no casting to long anywhere) and Math.random() to generate random numbers from Integer.MIN_VALUE to Integer.MAX_VALUE . Or if anyone know any random generators that don't get overflow internally?

The 'Math' library have Math.random() which generates a random value in [0, 1) range.

So don't use Math.random() - use this:

Random r = new Random();
int i = r.nextInt();

The docs for nextInt say:

nextInt() - Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. All 2^32 possible int values are produced with (approximately) equal probability.

It appears I misread the question slightly, and you need long not int - luckily the contract is the same.

long l = r.nextLong()

This will quite literally take two ints and jam them together to make a long.

更好的方法可能是使用java.security.SecureRandom ,它是一种加密强随机数生成器 (RNG)。

Random x = new Random(1000); // code running and generate values 1000 int i = x.nextInt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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