MyUserIsThis - 1 year ago 61
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

`rand()`
function in C++.

So it works like this: first I precalculate a bunch of probabilities that are of the form
`1/(1+exp(a))`
, for a set of different
`a`
. They're of type
`double`
as returned by the
`exp`
function in the
`math`
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
`0`
and
`1`
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);
``````

with
`N`
big enough such that the smallest division (
`1/N`
) is much smaller than the smallest probability
`1/1+exp(a)`
then I will be getting realistic random numbers.

I would like to understand why, though.

`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);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download