MyUserIsThis - 1 year ago 35

C Question

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

`rand()`

So it works like this: first I precalculate a bunch of probabilities that are of the form

`1/(1+exp(a))`

`a`

`double`

`exp`

`math`

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

so I'm given random values between

`0`

`1`

`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`

`1/N`

`1/1+exp(a)`

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