Generating Random Numbers between a potentially negative range

L

laura.paterson

Hi,

I have looked in the existing posts to try to find the solution to
this, but cannot find an answer...

I want to be able to create a random number within a certain range,
that may be partially or entirely negative, i.e. between 17 and 25, -17
and 25, -25 and 25... etc.

I have found various solutions using Math and Random, which would work
if both limits are either positive or negative, or if they are the same
distance form the origin, ie. -25, 25... but nothing that will work for
all range possibilities.

Any help will be much appreciated!
Thanks,
Laura
 
B

Bart Cremers

public static int nextInt(int low, int high) {
if (low > high) {
int tmp = low;
low = high;
high = tmp;
}

int diff = high - low;

int i = rnd.nextInt(diff);

return i + low;
}
 
B

Boris Stumm

Bart said:
public static int nextInt(int low, int high) {
if (low > high) {
int tmp = low;
low = high;
high = tmp;
}

int diff = high - low;

int i = rnd.nextInt(diff);

return i + low;
}

How about:
import static java.lang.Math.*;

public static int nextInt(int low, int high) {
return min(low, high) + rnd.nextInt(abs(high - low));
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top