[Qt-interest] Best Random Number Generator in Qt
Sean Harmer
sean.harmer at maps-technology.com
Thu Apr 15 14:14:14 CEST 2010
Hi,
On Thursday 15 April 2010 13:05:35 Aaron Lewis wrote:
> Hi,
> For example , i'd like to get a integer range from 0 to max , i can use
> such a function:
>
> int mpainter::getRandomNumber(int max)
> {
> return double(qrand()) / RAND_MAX * max;
> }
>
> But i don't think this is a good way to generate it , i always got a
> number two.
This is because the random number generator is only a pseudo random number
generator. If you do not seed it (or use the same seed) then you get the same
sequence of pseudo random numbers each time.
To get different sequences each time you run your application use the qsrand()
function to seed it with a different value each time. A common approach is to
seed it with the number of seconds since some time. For example:
qsrand( QDateTime::currentDateTime().toTime_t() );
Depending upon your needs though you may wish to use a completely different
pseudo random number generator. The last time I checked the built-in ones are
not particularly good for serious statistical work (e.g. Monte Carlo
simulations). They are fine for simple use cases though.
Cheers,
Sean
More information about the Qt-interest-old
mailing list