I want to generate random numbers between (0,1). I am trying the following:
double r2()
{
return((rand() % 10000) / 10000.0);
}
int SA()
{
double u;
u = r2();
}
But it doesn't generate the expected result. How can I fix it?
6 Answers 6
In your version rand() % 10000 will yield an integer between 0 and 9999. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.
It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG
double r2()
{
return (double)rand() / (double)RAND_MAX ;
}
Use (double)rand() / (double)((unsigned)RAND_MAX + 1) if exclusion of 1.0 was intentional.
1 Comment
Here's a general procedure for producing a random number in a specified range:
int randInRange(int min, int max)
{
return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}
Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.
6 Comments
(max-min+1) is 2 which means the rand() bit will return a number [0-2) which when truncated with (int) should roll 0 or 1 with equal probability.double in the range 0 to 1, and this returns an int. Also RAND_MAX + 1 may overflow.RAND_MAX + 1 can easily be INT_MIN or UB. Suggest (RAND_MAX/2 + 1)*2.0It seems to me you have not called srand first. Usage example here.
1 Comment
double r2()
{
return (rand() % 10001) / 10000.0;
}
Comments
Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?
As noted in another comment, SA() isn't returning anything explicitly.
http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html
From Generating random number between [-1, 1] in C?
((float)rand())/RAND_MAX returns a floating-point number in [0,1]
6 Comments
Have you tried with: replacing ((rand() % 10000) / 10000.0), with:(rand() % 2). This worked for me!
So you could do something like this:
double r2()
{
srand(time(NULL));
return(rand() % 2);
}
SA()does not return anything.uis not a "correct result"?