Thursday, January 21, 2010

Uniform (Pseudo) Random [0,1] Probability distribution in C++


Generating Uniform (Pseudo) Random Probability distribution in the interval [0,1] in C++:

double p = (RAND_MAX - rand()) / static_cast<double>(RAND_MAX);
--or--
double p = rand() / static_cast<double>(RAND_MAX);

Of course, use #include<cstdlib> for using int rand(); function and use void srand(int); to set the seed (if necessary).

Debugging tip:
---------------
Using a specific seed initially can help with repeating the random number patterns. Eg: srand(5); can be used in the program for debugging purposes and then removed later on!

No comments:

Back to Top


 

Labels