# Thread: Generating random numbers within an interval

1. Member
Join Date
Jan 2014
Posts
44
Rep Power
0

## 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:

Java Code:
`int guess = rand.nextInt(max - (min - 1)) + min;`
But I wonder, is this really the easiest way of writing it?
Last edited by Stud1; 01-13-2014 at 10:32 PM.

2. ## 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:

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

3. Señor Member
Join Date
Jan 2014
Posts
108
Rep Power
0

## 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
Java Code:
`math.random()`
That there is a way to do it. I seem to recall doing
Java Code:
`int random = (int) math.random() * 45 + 10;`
or something like that to get a random number between 10 and 55?

4. Member
Join Date
Jan 2014
Posts
44
Rep Power
0

## Re: Generating random numbers within an interval

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:

Java 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.

5. ## Re: Generating random numbers within an interval

It should. But it would not work if min > max.

6. Senior Member
Join Date
Jan 2013
Location
United States
Posts
2,728
Rep Power
4

## Re: Generating random numbers within an interval

s/math/Math

Regards,
Jim

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•