Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Random Number Generation - What (If Anything) Is Wrong With This

Tags:

c

random

For a simple simulation in C, I need to generate exponential random variables. I remember reading somewhere (but I can't find it now, and I don't remember why) that using the rand() function to generate random integers in a fixed range would generate non-uniformly distributed integers. Because of this, I'm wondering if this code might have a similar problem:

//generate u ~ U[0,1]
u = (   (double)rand() / ((double)(RAND_MAX));
//inverse of exponential CDF to get exponential random variable
expon = -log(1-u) * mean;

Thank you!

like image 372
user327301 Avatar asked Dec 28 '22 21:12

user327301


2 Answers

The problem with random numbers in a fixed range is that a lot of people do this for numbers between 100 and 200 for example:

100 + rand() % 100

That is not uniform. But by doing this it is (or is close enough to uniform at least):

u = 100 + 100 * ((double)rand() / ((double)(RAND_MAX));

Since that's what you're doing, you should be safe.

like image 107
Jakob Avatar answered May 30 '23 09:05

Jakob


In theory, at least, rand() should give you a discrete uniform distribution from 0 to RAND_MAX... in practice, it has some undesirable properties, such as a small period, so whether it's useful depends on how you're using it.

like image 32
WhirlWind Avatar answered May 30 '23 10:05

WhirlWind