# How to pick a random number between x and y

This is a discussion on How to pick a random number between x and y within the C Programming forums, part of the General Programming Boards category; I'm trying to learn C-programming by myself and this is the first thing i'm really having trouble with. So how ...

1. ## How to pick a random number between x and y

I'm trying to learn C-programming by myself and this is the first thing i'm really having trouble with. So how can i pick a random number for example between 1000 and 10 000?

2. search for rand() function

If you are just starting to learn C programming I think you should better start learning the basics first

3. Originally Posted by mahaju
search for rand() function

If you are just starting to learn C programming I think you should better start learning the basics first
I'm past the basics but i need something more than a mere name for the function.

4. Originally Posted by CMEE
I'm past the basics but i need something more than a mere name for the function.
Try this website
srand - C++ Reference
It has a lot of C++ references, but since it is backward compatible with C you will find information about many C functions as well

5. The basic formula is MAX - MIN + MIN. So something like this would work:

Code:
`int num_between_x_and_y = (rand() % (X - Y)) + Y;`

6. The most un-biased method of doing it is to use the rejection method. This is as follows:
Code:
```// Generates random number between min and max, inclusive.
int random(int min, int max)
{
int range, result, cutoff;

if (min >= max)
return min; // only one outcome possible, or invalid parameters
range = max-min+1;
cutoff = (RAND_MAX / range) * range;

// Rejection method, to be statistically unbiased.
do {
result = rand();
} while (result >= cutoff);

return result % range + min;
}```
The theory with the rejection method is easier to understand if you imagine a random number generator that generates a 4-bit random number and you want a random number with six equally probably outcomes (say for a die roll).
Throwing away the loop and using % alone, you get:

• 0 if rand() was 0, 6, or 12
• 1 if rand() was 1, 7, or 13
• 2 if rand() was 2, 8, or 14
• 3 if rand() was 3, 9, or 15
• 4 if rand() was 4 or 10
• 5 if rand() was 5 or 11

Notice how there are three ways to get 0-3 but only two ways of getting 4-5. This is statistically biased towards the lower numbers! So the rejection method would throw away any random number of 12 or above and try again. That way there are exactly two ways of arriving at each outcome. (The calculation for cutoff calculates 12 in this case due to the integer division result of 16 / 6 being 2, and 2 * 6 = 12)