Java: random long number in 0 <= x < n range

2019-01-05 00:01发布

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.

15条回答
Lonely孤独者°
2楼-- · 2019-01-05 00:29
public static long randomLong(long min, long max)
{
    try
    {
        Random  random  = new Random();
        long    result  = min + (long) (random.nextDouble() * (max - min));
        return  result;
    }
    catch (Throwable t) {t.printStackTrace();}
    return 0L;
}
查看更多
狗以群分
3楼-- · 2019-01-05 00:31

If you want a uniformly distributed pseudorandom long in the range of [0,m), try using the modulo operator and the absolute value method combined with the nextLong() method as seen below:

Math.abs(rand.nextLong()) % m;

Where rand is your Random object.

The modulo operator divides two numbers and outputs the remainder of those numbers. For example, 3 % 2 is 1 because the remainder of 3 and 2 is 1.

Since nextLong() generates a uniformly distributed pseudorandom long in the range of [-(2^48),2^48) (or somewhere in that range), you will need to take the absolute value of it. If you don't, the modulo of the nextLong() method has a 50% chance of returning a negative value, which is out of the range [0,m).

What you initially requested was a uniformly distributed pseudorandom long in the range of [0,100). The following code does so:

Math.abs(rand.nextLong()) % 100;
查看更多
乱世女痞
4楼-- · 2019-01-05 00:36

Thank you so much for this post. It is just what I needed. Had to change something to get the part I used to work.

I got the following (included above):

long number = x+((long)r.nextDouble()*(y-x));

to work by changing it to:

long number = x+ (long)(r.nextDouble()*(y-x));

since (long)r.nextDouble() is always zero.

查看更多
登录 后发表回答