Java: Random long value in an interval

24,222

Solution 1

If you want range based long values then do the below:

 long LOWER_RANGE = 0; //assign lower range value
 long UPPER_RANGE = 1000000; //assign upper range value
 Random random = new Random();


 long randomValue = LOWER_RANGE + 
                           (long)(random.nextDouble()*(UPPER_RANGE - LOWER_RANGE));

Solution 2

You could use nextInt to generate higher and lower ints of the long. It's even possible to extend the Random-class with your own nextLong-method (even though composition could be a safer choice for more serious programming).

Take a look at the Javadoc of nextInt(int n). A nextLong method could be implemented using the same algorithm. Getting it right could prove a bit tricky. Prepare to do some math with pen and paper. Using a proven library is wise if you're not just coding for fun.

Share:
24,222
Mintz
Author by

Mintz

Updated on June 15, 2020

Comments

  • Mintz
    Mintz almost 4 years

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

    I want to generate a random long value in an interval but it seems that the Random class nextLong() doesn't accept arguments like nextInt(). What can I do here?

  • Vishy
    Vishy over 11 years
    +1 Its worth noting that Random uses a 48-bit seed so it won't generate all possible double or long. SecureRandom is slow but will generate all possible values.
  • St.Antario
    St.Antario over 8 years
    Why didn't you use nextLong()?
  • Stefan Reich
    Stefan Reich almost 8 years
    This is not correct; it will return values larger than n on occasion.
  • COME FROM
    COME FROM almost 8 years
    @StefanReich True. Low bits of n will be ignored. I'll edit the answer.
  • COME FROM
    COME FROM almost 8 years
    @StefanReich I removed the bad example.