[c] How to generate a random number between 0 and 1?

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?

This question is related to c

The answer is


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);
}

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.


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.


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

Edit: From Generating random number between [-1, 1] in C? ((float)rand())/RAND_MAX returns a floating-point number in [0,1]


double r2()
{
   return (rand() % 10001) / 10000.0;
}

It seems to me you have not called srand first. Usage example here.