Results 1 to 3 of 3

Thread: opimize random

  1. #1
    Join Date
    Jan 2006
    Posts
    273
    Thanks
    42
    Thanked 1 Time in 1 Post
    Qt products
    Qt3 Qt4
    Platforms
    Windows

    Default opimize random

    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

    Qt Code:
    1. int max;
    2. QSqlQuery count("select count(words_id) from words_tbl");
    3. while(count.next())
    4. {
    5. max = count.value(0).toInt();
    6. }
    7.  
    8. //random
    9. int a = (1 + ( rand() % ( max - 1 + 1 ) ));
    10. QString b = QString::number(a);
    To copy to clipboard, switch view to plain text mode 
    Think DigitalGasoline

  2. #2
    Join Date
    Jan 2006
    Location
    Warsaw, Poland
    Posts
    33,359
    Thanks
    3
    Thanked 5,015 Times in 4,792 Posts
    Qt products
    Qt3 Qt4 Qt5 Qt/Embedded
    Platforms
    Unix/X11 Windows Android Maemo/MeeGo
    Wiki edits
    10

    Default Re: opimize random

    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...

  3. #3
    Join Date
    Feb 2006
    Location
    Romania
    Posts
    2,744
    Thanks
    8
    Thanked 541 Times in 521 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: opimize random

    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 .

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.