PDA

View Full Version : opimize random



raphaelf
15th May 2007, 15:33
Hello everybody,

I am able to generate a number..

But i get for example number 5 and 6 a lot, and 1 or 3 never..

How could i optimized my random?

Thanks



int max;
QSqlQuery count("select count(words_id) from words_tbl");
while(count.next())
{
max = count.value(0).toInt();
}

//random
int a = (1 + ( rand() % ( max - 1 + 1 ) ));
QString b = QString::number(a);

wysota
15th May 2007, 23:33
Optimize? :) Did you use srand() first to set the seed of the random number generator? Because if you didn't your numbers will be likely predictable...

marcel
16th May 2007, 00:01
rand() will return large numbers typically. If max is a small value ( smaller than 10?, even bigger ), the number distribution will be limited.
I mean that rand() will not repeat itself but rand()%max will. There isn't much you acn do about this, but to request another number if the average apparitions of the current number are too big( which I'm sure you don't want to do ).

Well, random is not that easy :).