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.
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 thenextLong()
method as seen below:Where
rand
is your Random object.The modulo operator divides two numbers and outputs the remainder of those numbers. For example,
3 % 2
is1
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 thenextLong()
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:
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):
to work by changing it to:
since
(long)r.nextDouble()
is always zero.