views:

26170

answers:

14

Hello,

I am trying to generate a random number with Java, but random in a specific range. For example, my range is 5-10, meaning that 5 is the smallest possible value the random number can take, and 10 is the biggest. Any other number in between these numbers is possible to be a value, too.

In Java, there is a function random() in the Math class, which returns a double value between 0.0 and 1.0. In the class Random there is a function nextInt(int n), which returns a random value in the range of 0 (inclusive) and n (exclusive). I couldn't find a method, which returns a random value between two numbers.

I have tried the following things, but I still have problems: (minimum and maximum are the smallest and biggest numbers).

Solution 1 :

randomNum = minimum + (int)(Math.random()*maximum);

problem: randomNum takes is assinged values numbers bigger that maximum

Solution 2 :

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

problem: randomNum takes is assigned values smaller than minimum.

Could you suggest how to solve my problem, or point me to some references? I have tried also browsing through the archive, and found:

but I couldn't solve the problem.

Thank you.

+2  A: 

how about minimum + rn.nextInt(maxValue - minvalue + 1) ?

krosenvold
Side note - this generator is exclusive of maxValue. Simple to fix, though.
Greg Case
That should be maxValue - minvalue + 1.
Robert Gamble
Thanks a lot! Yes, this works fine if I add +1:minimum + rn.nextInt(maximum - minimum + 1)
+21  A: 

The standard way to do this is as follows:

// Example assumes these variables have been initialized
// above, e.g. as method parameters or otherwise
Random rand;
int min, max;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt(max - min + 1) + min;
Greg Case
Minor note - you have to say "rand = new Random()" at some point, otherwise you'll get an NPE.
Adam Rosenfield
I use the declarations at the top simply to state that the variables exist and what their types are, since exactly how they're initialized in unimportant to the question being asked.
Greg Case
True, which is why it's only a minor note. I usually add a ... in my code snippets to indicate something like that.
Adam Rosenfield
I have corrected the NPE
matt b
I've rolled back the change, but clarified the assumption within the example so it is more clear.
Greg Case
In an array of max where min = 0, i get an array out of bounds exception
Matt R
Matt - can you add a little more detail? The above snippet does not use any arrays.
Greg Case
+2  A: 

Try

rand.nextInt((max+1) - min) + min;
Michael Myers
Off by one---you never get "max" as an output.
erickson
Ah, that explains why Greg Case's answer had a strange +1 in it. I should read the question more closely.
Michael Myers
Y'know, I almost put a comment in the example to explain the +1...
Greg Case
+1  A: 

I wonder if any of the random number generating methods provided by an Apache Commons library would fit the bill.

For example: nextInt or nextLong

Chinnery
A: 
int random = minimum + Double.valueOf(Math.random()*(maximum-minimun)).intValue();

Or take a look to RandomUtils from apache commons

http://commons.apache.org/lang

damian
I wouldn't use Apache Commons to generate random numbers. RandomUtils is extremely poorly implemented (see http://blog.uncommons.org/2007/06/29/the-tragedy-of-the-jakarta-commons/)
Dan Dyer
+1  A: 

You can edit your second code example to:

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;
Bill the Lizard
+26  A: 

One standard pattern for accomplishing this is:

Min + (int)(Math.random() * ((Max - Min) + 1))

The java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

In order to get a specific range of values first you need to multiply by the magnitude of the range of values you want covered.

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min).

For example if you want [5,10] you need cover 5 integer values so you use

Math.random() * 5

This would return a value in the range [0,5)

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

Min + (Math.random() * (Max - Min))

You now will get a value in the range [Min,Max). But this is still doesn't include max and you are getting a double value. In order to get the max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

Min + (int)(Math.random() * ((Max - Min) + 1))

And there you have it. A random integer value in the range [Min,Max].

TJ_Fischer
Nice explanation!
The `Random.nextInt(n)`-based answer is much better than this.
polygenelubricants
A: 

Thanks a lot for the replies!

A: 

When you need a lot of random number I do not recommend the Random class in the API. It has just a too small period. Try MersenneTwister instead. You can get a java implementation here.

+1  A: 

The Math.Random class in java is 0-based. So, if you write something like

Random rand = new Random();
int x = rand.NextInt(10);

x will be between 0-9 inclusive.

So given the following array of 25 items, the code to generate a random number between 0 (the base of the array) and array.length would be:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.NextInt(i.Length)

Since i.Length will return 25, the NextInt(i.Length) will return a number between the range of 0-24. The other option is going with the Math.Random which works in the same way.

   index = (int)Math.floor(Math.random()*i.length);

For a better understanding, check out this post.

Matt R
+1  A: 
    Random ran = new Random();

int x = ran.nextInt(5) + 5;

the integer x is now the random that has a possible outcome of 5-10.

A: 

Thanx for the solution... it's help me very much....

A: 

use : in case of rolling a dice it would be ramdom number between 1 to 6 (not 0 to 6) so face = 1 + randomNumbers.nextInt(6);

sam
A: 

rand.nextInt((max+1) - min) + min;

this is working fine.........

ganesh