MyUserIsThis MyUserIsThis - 1 year ago 35
C Question

About a criteria for random integers number generation (C)

I am running a bunch of physical simulations in which I need random numbers. I'm using the standard

function in C++.

So it works like this: first I precalculate a bunch of probabilities that are of the form
, for a set of different
. They're of type
as returned by the
function in the
library, and then things must happen with those probabilities, there are only two of them, so I generate a random number uniformly distributed between 0 and 1 and compared with those precalculated probabilities. To do that, I used:

double p = double(rand()%101)/100.0;

so I'm given random values between
both included. This didn't yield to correct physical results. I tried this:

double p = double(rand()%1000001)/1000000.0;

And this worked. I don't really understand why so I would like some criteria about how to do it. My intuition tells that if I do

double p = double(rand()%(N+1))/double(N);

big enough such that the smallest division (
) is much smaller than the smallest probability
then I will be getting realistic random numbers.

I would like to understand why, though.

Answer Source

rand() returns a random number between 0 and RAND_MAX.

Therefore you need this:

double p = double(rand() % RAND_MAX) / double(RAND_MAX);

Also run this snippet and you will understand:

  int i;

  for (i = 1; i < 30; i++)
      int rnd = rand();
      double p0 = double(rnd % 101) / 100.0;
      double p1 = double(rnd % 1000001) / 1000000.0;
      printf ("%d\t%f\t%f\n", rnd, p0, p1);

  for (i = 1; i < 30; i++)
      int rnd = rand();
      double p0 = double(rnd) / double(RAND_MAX);
      printf ("%d\t%f\n", rnd, p0);