qt random number



  • in C++
    srand(time(NULL));
    rand()%2+0; // generates random 1 and 0

    how can i write this in QT? when i use qsrand and qrand i always get the same random numbers everytime the program is started.

    i want to use QT for random generation so it is all interpreted the same on different platforms


  • Moderators

    @Lorence
    How do you set the seed?
    Respectively, what are you using for setting the seed?



  • The c++11 random number generator is random, not pseudo random and unless you are running an embedded system should be available.


  • Qt Champions 2016

    @mjsurette
    This is news to me, could you provide a verifiable source for that statement? Maybe I'm not up to date, but as far as I know in C++11 you still seed the sequence, which would mean you have pseudo-random generation.



  • this is how i write it in qt

    qsrand(0);
    qrand() % 2 + 0;


  • Qt Champions 2016

    @Lorence
    You have to use a different seed every time you start your program to get a different sequence of numbers. Otherwise you'll get the same sequence (hence the name: pseudo-random number generator). You could use something like this to initialize your sequence:

    // Initialize sequence
    qsrand(QDateTime::currentMSecsSinceEpoch() / 1000);
    // ... Generate numbers from that sequence
    qrand();
    // ...
    qrand();
    // ...
    



  • Moderators

    @Lorence said:

    this is how i write it in qt

    qsrand(0);
    qrand() % 2 + 0;

    Not much to add to the other responses.
    In your C++ example you are using the current time as seed. Since there is between different trials always another time you will have everytime also another sequence of pseudo-random numbers.

    In your Qt example above you are using always '0' as a seed and therefore you will always get the identical sequence of pseudo-random numbers.


  • Qt Champions 2016

    @mjsurette
    With the important note:

    Notice that random devices may not always be available to produce random numbers (and in some systems, they may even never be available). This is signaled by throwing an exception derived from the standard exception on construction or when a number is requested with operator().
    Unless the program really requires a stochastic process to generate random numbers, a portable program is encouraged to use an alternate pseudo-random number generator engine instead, or at least provide a recovery method for such exceptions.

    Windows will not provide real random numbers (at least to my knowledge), and in Linux this is implementation dependent. Even if /dev/random is advertised to produce real random numbers, the truthfulness of such a statement is debatable. Often enough the random device just generates a pseudo-random sequence. That's why you get the above note on portability.

    Kind regards.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.