Dave Copperfield
Dave Copperfield

Reputation: 11

Output Random Number in range when using rand()

My Specific question is when i input a range like 90 as the lower value and 100 as the higher value i get output random number sometimes less than 90.In my code below , x<y. My code is:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define Null 0

void main(){
    int x,y,a,b;
    printf("Insert two numbers to create a range\n in which you want a random number to be generated:\n");
    scanf("%d%d",&x,&y);
    srand(time(Null));
    a =( rand() + x)%y ;
    printf("The Randomly Generated Number is %d.\n",a);


}

Upvotes: 0

Views: 595

Answers (4)

Grady Player
Grady Player

Reputation: 14549

assuming you want an actual random distribution... psudeocode

range = high - low
r = rand()
while (r > range)
{
    r=rand();
}
r+=low;

something like that should give you a uniform distribution by rejecting things out of range, because using mod n there isn't a uniform distribution for all values of n over rand's domain (0 to RAND_MAX which is 0x7fffffff on my C library).

lets use the contrived example of 0xf as the domain:

if you do rand() % 10 for every value in the range... then you get: 0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5. which has 2* as many 0,1,2,3,4,5 as 6,7,7,8,9...

by going to a larger domain you get smoother distribution, but it will always be lumpy if you aren't modding by something that cleanly divides RAND_MAX+1

depending on the numbers you are working on and how fast rand is you could do something simplistic like above or you could discard things above the largest number that divides cleanly by your divisor... so discard everything over 0x7FFFFFF8 if you are dividing by 10 to get rid of bias.

Upvotes: -1

Lahcen YAMOUN
Lahcen YAMOUN

Reputation: 691

You have to use this formula for the y exclusive ( a in [x , y[ ):

a = (rand() % (y - x)) + x;

and this one for the y inclusive ( a in [x , y] ):

a = (rand() % (y - x + 1)) + x;

Upvotes: 1

Ryan Haining
Ryan Haining

Reputation: 36802

Assuming you want an exclusive upper bound the right way to do this is:

(rand() % (high - low)) + low

Assuming high=100 and low=90, walking through how this works:

  • you generate a random int
  • (high - low) gives you the range, 100 - 90 = 10.
  • When you % by 10, you are going to get a result in the range [0, 10), so it will be one of 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9
  • Since what you really want is one of 90, 91, 92, ..., 99 you have to add low back to it

The thing to note here is that you will only get [90, 99]. If you want to have an inclusive upperbound so [90, 100] then you want to add 1 to the amount you are modding by

(rand() % (high + 1 - low)) + low

Upvotes: 3

MrGreen
MrGreen

Reputation: 499

Edit: It should be:

if (x == y) a = x
else a = (rand() % (y - x)) + x

Upvotes: 0

Related Questions