How to generate random number in Qt

If you thought Qt provided you with a robust count of math algorithms already, you’ll be in for a surprise. There is qrand(), but it doesn’t quite provide you with the user-friendliness of other languages. For example, sometimes you want a random number that is negative. Sure, you can do this all manually, but then you’d have to write your own function. Unfortunately, that’s exactly what you’ll have to do.

http://developer.nokia.com/Community/Wiki/Generating_random-value_integers_in_Qt

#include <QGlobal.h>
#include <QTime>

int QMyClass::randInt(int low, int high)
{
// Random number between low and high
return qrand() % ((high + 1) - low) + low;
}

// Create seed for the random
// That is needed only once on application startup
QTime time = QTime::currentTime();
qsrand((uint)time.msec());

// Get random value between 0-100
int randomValue = randInt(0,100);

It is recommended that you don’t use qrand() by default if you want to generate encryption-level random numbers.

So, with that code, now you can set a range of numbers which you can pull random numbers from. Make note that qsrand() only sets the seed and you should only do that once.

2 Replies to “How to generate random number in Qt”

  1. This is not a very good method to generate random numbers within a given range.(In fact its veryvery bad for most generators )

    You are assuming that the low-order bits from the generator are uniformly distributed . This is not the case with most generators.

    You should scale using multiplication and division. Not using the modulo operator.
    eg

    my_number= start_required + ( generator_output * range_required)/generator_maximum;

    if generator_output is in [0, generator_maximum]
    my_number will be in [start_required , start_required + range_required]

    1. Unfortunately, it is what comes with Qt and that’s sufficient for my needs (game engine). If it was being used to implement security, then I agree it should be more complex.

Comments are closed.