# Generating random numbers within an interval

• 01-13-2014, 10:30 PM
Stud1
Generating random numbers within an interval
I've been trying to find the easiest way to write to generate a number which is between intervals of a arbitrary min and a max value.

I've been searching for this but I don't find this particular thing.

I've found that this combination works:

Code:

`int guess = rand.nextInt(max - (min - 1)) + min;`
But I wonder, is this really the easiest way of writing it?
• 01-13-2014, 11:17 PM
kjkrum
Re: Generating random numbers within an interval
Your code may be wrong, but that depends exactly how you are defining min and max. If both ends of the range are inclusive, then you've written it correctly. As always, you can split up complex statements into multiple lines:

Code:

```int range = max - min + 1; // omit +1 if max is exclusive int guess = min + rand.nextInt(range);```
• 01-14-2014, 12:08 AM
AlexGraal
Re: Generating random numbers within an interval
Maybe I'm wrong and this isn't doable this way, but I'm pretty sure that if you read up on
Code:

`math.random()`
That there is a way to do it. I seem to recall doing
Code:

`int random = (int) math.random() * 45 + 10;`
or something like that to get a random number between 10 and 55?
• 01-14-2014, 12:04 PM
Stud1
Re: Generating random numbers within an interval
Quote:

Originally Posted by kjkrum
Your code may be wrong, but that depends exactly how you are defining min and max. If both ends of the range are inclusive, then you've written it correctly. As always, you can split up complex statements into multiple lines:

Code:

```int range = max - min + 1; // omit +1 if max is exclusive int guess = min + rand.nextInt(range);```

Yes both ends of the range should be inclusive. Thanks for clarifying.

Just to clarify, does this work also for negative numbers? It seems it does when I try but I want to make sure.
• 01-14-2014, 06:54 PM
kjkrum
Re: Generating random numbers within an interval
It should. But it would not work if min > max.
• 01-14-2014, 06:58 PM
jim829
Re: Generating random numbers within an interval
s/math/Math

Regards,
Jim