Qt Snippet: random number generator


In case you need to get a random number Qt provide the "classic" pseudo random generator based to an initial seed number. A pseudo random number is a simply algorithm able to generate a list of different numbers based to an initial number value called "seed".



Please note that in this case using the same seed number multiple times will have the consequence that the sequence of numbers generated will be always the same every time. For this reasons is very important to set a "casual" seed number at each new call. The common practice is to use the current millisecond time at the moment of initialization call as follow:

qsrand(static_cast<uint>(QTime::currentTime().msec()));

The qsrand() function must to be call only once usually at program startup. Another important note is this function is thread dependent. This mean you have to call this function for set the seed number from inside the thread where you'll need to get the random numbers. For example in case you need to get a random number in the main thread and in a secondary thread you'll have to call srand() two times at beginning of both threads. Once clarified this point the function for get a random number included between a min and max value is the following:

int GetRandomNumber(const int Min, const int Max)
{
    return ((qrand() % ((Max + 1) - Min)) + Min);
}

Each time you'll call this function you'll get a different number in the requested range.

0 Comments:

Post a Comment