QRandomGenerator Class

The QRandomGenerator class allows one to obtain random values from a high-quality Random Number Generator. More...

Header: #include <QRandomGenerator>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Inherited By:

QRandomGenerator64

Note: All functions in this class are reentrant.

Note: These functions are also thread-safe:

Public Types

Public Functions

QRandomGenerator(quint32 seedValue = 1)
QRandomGenerator(const quint32 (&)[N] seedBuffer)
QRandomGenerator(std::seed_seq &sseq)
QRandomGenerator(const quint32 *begin, const quint32 *end)
QRandomGenerator(const quint32 *seedBuffer, qsizetype len)
QRandomGenerator(const QRandomGenerator &other)
double bounded(double highest)
int bounded(int highest)
qint64 bounded(qint64 highest)
quint32 bounded(quint32 highest)
quint64 bounded(quint64 highest)
int bounded(int lowest, int highest)
qint64 bounded(int lowest, qint64 highest)
qint64 bounded(qint64 lowest, int highest)
qint64 bounded(qint64 lowest, qint64 highest)
quint32 bounded(quint32 lowest, quint32 highest)
quint64 bounded(quint64 lowest, quint64 highest)
quint64 bounded(quint64 lowest, unsigned int highest)
quint64 bounded(unsigned int lowest, quint64 highest)
void discard(unsigned long long z)
void fillRange(UInt (&)[N] buffer)
void fillRange(UInt *buffer, qsizetype count)
quint64 generate64()
quint32 generate()
void generate(ForwardIterator begin, ForwardIterator end)
double generateDouble()
void seed(quint32 seed = 1)
void seed(std::seed_seq &seed)
QRandomGenerator::result_type operator()()

Static Public Members

QRandomGenerator *global()
QRandomGenerator::result_type max()
QRandomGenerator::result_type min()
QRandomGenerator securelySeeded()
QRandomGenerator *system()
bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)

Detailed Description

QRandomGenerator may be used to generate random values from a high-quality random number generator. Like the C++ random engines, QRandomGenerator can be seeded with user-provided values through the constructor. When seeded, the sequence of numbers generated by this class is deterministic. That is to say, given the same seed data, QRandomGenerator will generate the same sequence of numbers. But given different seeds, the results should be considerably different.

QRandomGenerator::securelySeeded() can be used to create a QRandomGenerator that is securely seeded with QRandomGenerator::system(), meaning that the sequence of numbers it generates cannot be easily predicted. Additionally, QRandomGenerator::global() returns a global instance of QRandomGenerator that Qt will ensure to be securely seeded. This object is thread-safe, may be shared for most uses, and is always seeded from QRandomGenerator::system()

QRandomGenerator::system() may be used to access the system's cryptographically-safe random generator. On Unix systems, it's equivalent to reading from /dev/urandom or the getrandom() or getentropy() system calls.

The class can generate 32-bit or 64-bit quantities, or fill an array of those. The most common way of generating new values is to call the generate(), generate64() or fillRange() functions. One would use it as:

    quint32 value = QRandomGenerator::global()->generate();

Additionally, it provides a floating-point function generateDouble() that returns a number in the range [0, 1) (that is, inclusive of zero and exclusive of 1). There's also a set of convenience functions that facilitate obtaining a random number in a bounded, integral range.

Seeding and determinism

QRandomGenerator may be seeded with specific seed data. When that is done, the numbers generated by the object will always be the same, as in the following example:

    QRandomGenerator prng1(1234), prng2(1234);
    Q_ASSERT(prng1.generate() == prng2.generate());
    Q_ASSERT(prng1.generate64() == prng2.generate64());

The seed data takes the form of one or more 32-bit words. The ideal seed size is approximately equal to the size of the QRandomGenerator class itself. Due to mixing of the seed data, QRandomGenerator cannot guarantee that distinct seeds will produce different sequences.

QRandomGenerator::global(), like all generators created by QRandomGenerator::securelySeeded(), is always seeded from QRandomGenerator::system(), so it's not possible to make it produce identical sequences.

Bulk data

When operating in deterministic mode, QRandomGenerator may be used for bulk data generation. In fact, applications that do not need cryptographically-secure or true random data are advised to use a regular QRandomGenerator instead of QRandomGenerator::system() for their random data needs.

For ease of use, QRandomGenerator provides a global object that can be easily used, as in the following example:

    int x = QRandomGenerator::global()->generate();
    int y = QRandomGenerator::global()->generate();
    int w = QRandomGenerator::global()->bounded(16384);
    int h = QRandomGenerator::global()->bounded(16384);

System-wide random number generator

QRandomGenerator::system() may be used to access the system-wide random number generator, which is cryptographically-safe on all systems that Qt runs on. This function will use hardware facilities to generate random numbers where available. On such systems, those facilities are true Random Number Generators. However, if they are true RNGs, those facilities have finite entropy sources and thus may fail to produce any results if their entropy pool is exhausted.

If that happens, first the operating system then QRandomGenerator will fall back to Pseudo Random Number Generators of decreasing qualities (Qt's fallback generator being the simplest). Whether those generators are still of cryptographic quality is implementation-defined. Therefore, QRandomGenerator::system() should not be used for high-frequency random number generation, lest the entropy pool become empty. As a rule of thumb, this class should not be called upon to generate more than a kilobyte per second of random data (note: this may vary from system to system).

If an application needs true RNG data in bulk, it should use the operating system facilities (such as /dev/random on Linux) directly and wait for entropy to become available. If the application requires PRNG engines of cryptographic quality but not of true randomness, QRandomGenerator::system() may still be used (see section below).

If neither a true RNG nor a cryptographically secure PRNG are required, applications should instead use PRNG engines like QRandomGenerator's deterministic mode and those from the C++ Standard Library. QRandomGenerator::system() can be used to seed those.

Fallback quality

QRandomGenerator::system() uses the operating system facilities to obtain random numbers, which attempt to collect real entropy from the surrounding environment to produce true random numbers. However, it's possible that the entropy pool becomes exhausted, in which case the operating system will fall back to a pseudo-random engine for a time. Under no circumstances will QRandomGenerator::system() block, waiting for more entropy to be collected.

The following operating systems guarantee that the results from their random-generation API will be of at least cryptographically-safe quality, even if the entropy pool is exhausted: Apple OSes (Darwin), BSDs, Linux, Windows. Barring a system installation problem (such as /dev/urandom not being readable by the current process), QRandomGenerator::system() will therefore have the same guarantees.

On other operating systems, QRandomGenerator will fall back to a PRNG of good numeric distribution, but it cannot guarantee proper seeding in all cases. Please consult the OS documentation for more information.

Applications that require QRandomGenerator not to fall back to non-cryptographic quality generators are advised to check their operating system documentation or restrict their deployment to one of the above.

Reentrancy and thread-safety

QRandomGenerator is reentrant, meaning that multiple threads can operate on this class at the same time, so long as they operate on different objects. If multiple threads need to share one PRNG sequence, external locking by a mutex is required.

The exceptions are the objects returned by QRandomGenerator::global() and QRandomGenerator::system(): those objects are thread-safe and may be used by any thread without external locking. Note that thread-safety does not extend to copying those objects: they should always be used by reference.

Standard C++ Library compatibility

QRandomGenerator is modeled after the requirements for random number engines in the C++ Standard Library and may be used in almost all contexts that the Standard Library engines can. Exceptions to the requirements are the following:

  • QRandomGenerator does not support seeding from another seed sequence-like class besides std::seed_seq itself;
  • QRandomGenerator is not comparable (but is copyable) or streamable to std::ostream or from std::istream.

QRandomGenerator is also compatible with the uniform distribution classes std::uniform_int_distribution and std:uniform_real_distribution, as well as the free function std::generate_canonical. For example, the following code may be used to generate a floating-point number in the range [1, 2.5):

    std::uniform_real_distribution dist(1, 2.5);
    return dist(*QRandomGenerator::global());

See also QRandomGenerator64.

Member Type Documentation

QRandomGenerator::result_type

A typedef to the type that operator() returns. That is, quint32.

See also operator().

Member Function Documentation

qint64 QRandomGenerator::bounded(int lowest, qint64 highest)

qint64 QRandomGenerator::bounded(qint64 lowest, int highest)

quint64 QRandomGenerator::bounded(quint64 lowest, unsigned int highest)

quint64 QRandomGenerator::bounded(unsigned int lowest, quint64 highest)

This is an overloaded function.

This function exists to help with overload resolution when the types of the parameters don't exactly match. They will promote the smaller type to the type of the larger one and call the correct overload.

QRandomGenerator::QRandomGenerator(quint32 seedValue = 1)

Initializes this QRandomGenerator object with the value seedValue as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.

See also seed() and securelySeeded().

template <qsizetype N> QRandomGenerator::QRandomGenerator(const quint32 (&)[N] seedBuffer)

This is an overloaded function.

Initializes this QRandomGenerator object with the values found in the array seedBuffer as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.

See also seed() and securelySeeded().

[noexcept] QRandomGenerator::QRandomGenerator(std::seed_seq &sseq)

This is an overloaded function.

Initializes this QRandomGenerator object with the seed sequence sseq as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.

See also seed() and securelySeeded().

QRandomGenerator::QRandomGenerator(const quint32 *begin, const quint32 *end)

This is an overloaded function.

Initializes this QRandomGenerator object with the values found in the range from begin to end as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.

This constructor is equivalent to:

    std::seed_seq sseq(begin, end);
    QRandomGenerator generator(sseq);

See also seed() and securelySeeded().

QRandomGenerator::QRandomGenerator(const quint32 *seedBuffer, qsizetype len)

This is an overloaded function.

Initializes this QRandomGenerator object with len values found in the array seedBuffer as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.

This constructor is equivalent to:

    std::seed_seq sseq(seedBuffer, seedBuffer + len);
    QRandomGenerator generator(sseq);

See also seed() and securelySeeded().

QRandomGenerator::QRandomGenerator(const QRandomGenerator &other)

Creates a copy of the generator state in the other object. If other is QRandomGenerator::system() or a copy of that, this object will also read from the operating system random-generating facilities. In that case, the sequences generated by the two objects will be different.

In all other cases, the new QRandomGenerator object will start at the same position in the deterministic sequence as the other object was. Both objects will generate the same sequence from this point on.

For that reason, it is not advisable to create a copy of QRandomGenerator::global(). If one needs an exclusive deterministic generator, consider instead using securelySeeded() to obtain a new object that shares no relationship with the QRandomGenerator::global().

double QRandomGenerator::bounded(double highest)

Generates one random double in the range between 0 (inclusive) and highest (exclusive). This function is equivalent to and is implemented as:

    return generateDouble() * highest;

If the highest parameter is negative, the result will be negative too; if it is infinite or NaN, the result will be infinite or NaN too (that is, not random).

See also generateDouble() and bounded().

int QRandomGenerator::bounded(int highest)

This is an overloaded function.

Generates one random 32-bit quantity in the range between 0 (inclusive) and highest (exclusive). highest must be positive.

Note that this function cannot be used to obtain values in the full 32-bit range of int. Instead, use generate() and cast to int.

See also generate(), generate64(), and generateDouble().

qint64 QRandomGenerator::bounded(qint64 highest)

This is an overloaded function.

Generates one random 64-bit quantity in the range between 0 (inclusive) and highest (exclusive). highest must be positive.

Note that this function cannot be used to obtain values in the full 64-bit range of qint64. Instead, use generate64() and cast to qint64 or instead use the unsigned version of this function.

Note: This function is implemented as a loop, which depends on the random value obtained. On the long run, on average it should loop just under 2 times, but if the random generator is defective, this function may take considerably longer to execute.

See also generate(), generate64(), and generateDouble().

quint32 QRandomGenerator::bounded(quint32 highest)

This is an overloaded function.

Generates one random 32-bit quantity in the range between 0 (inclusive) and highest (exclusive). The same result may also be obtained by using std::uniform_int_distribution with parameters 0 and highest - 1. That class can also be used to obtain quantities larger than 32 bits; for 64 bits, the 64-bit bounded() overload can be used too.

For example, to obtain a value between 0 and 255 (inclusive), one would write:

    quint32 v = QRandomGenerator::global()->bounded(256);

Naturally, the same could also be obtained by masking the result of generate() to only the lower 8 bits. Either solution is as efficient.

Note that this function cannot be used to obtain values in the full 32-bit range of quint32. Instead, use generate().

See also generate(), generate64(), and generateDouble().

quint64 QRandomGenerator::bounded(quint64 highest)

This is an overloaded function.

Generates one random 64-bit quantity in the range between 0 (inclusive) and highest (exclusive). The same result may also be obtained by using std::uniform_int_distribution<quint64> with parameters 0 and highest - 1.

Note that this function cannot be used to obtain values in the full 64-bit range of quint64. Instead, use generate64().

Note: This function is implemented as a loop, which depends on the random value obtained. On the long run, on average it should loop just under 2 times, but if the random generator is defective, this function may take considerably longer to execute.

See also generate(), generate64(), and generateDouble().

int QRandomGenerator::bounded(int lowest, int highest)

This is an overloaded function.

Generates one random 32-bit quantity in the range between lowest (inclusive) and highest (exclusive), both of which may be negative, but highest must be greater than lowest.

Note that this function cannot be used to obtain values in the full 32-bit range of int. Instead, use generate() and cast to int.

See also generate(), generate64(), and generateDouble().

qint64 QRandomGenerator::bounded(qint64 lowest, qint64 highest)

This is an overloaded function.

Generates one random 64-bit quantity in the range between lowest (inclusive) and highest (exclusive), both of which may be negative, but highest must be greater than lowest.

Note that this function cannot be used to obtain values in the full 64-bit range of qint64. Instead, use generate64() and cast to qint64.

Note: This function is implemented as a loop, which depends on the random value obtained. On the long run, on average it should loop just under 2 times, but if the random generator is defective, this function may take considerably longer to execute.

See also generate(), generate64(), and generateDouble().

quint32 QRandomGenerator::bounded(quint32 lowest, quint32 highest)

This is an overloaded function.

Generates one random 32-bit quantity in the range between lowest (inclusive) and highest (exclusive). The highest parameter must be greater than lowest.

The same result may also be obtained by using std::uniform_int_distribution with parameters lowest and \a highest - 1. That class can also be used to obtain quantities larger than 32 bits.

For example, to obtain a value between 1000 (incl.) and 2000 (excl.), one would write:

    quint32 v = QRandomGenerator::global()->bounded(1000, 2000);

Note that this function cannot be used to obtain values in the full 32-bit range of quint32. Instead, use generate().

See also generate(), generate64(), and generateDouble().

quint64 QRandomGenerator::bounded(quint64 lowest, quint64 highest)

This is an overloaded function.

Generates one random 64-bit quantity in the range between lowest (inclusive) and highest (exclusive). The highest parameter must be greater than lowest.

The same result may also be obtained by using std::uniform_int_distribution<quint64> with parameters lowest and \a highest - 1.

Note that this function cannot be used to obtain values in the full 64-bit range of quint64. Instead, use generate64().

Note: This function is implemented as a loop, which depends on the random value obtained. On the long run, on average it should loop just under 2 times, but if the random generator is defective, this function may take considerably longer to execute.

See also generate(), generate64(), and generateDouble().

void QRandomGenerator::discard(unsigned long long z)

Discards the next z entries from the sequence. This method is equivalent to calling generate() z times and discarding the result, as in:

    while (z--)
        generator.generate();

template <typename UInt, size_t N, QRandomGenerator::IfValidUInt<UInt> = true> void QRandomGenerator::fillRange(UInt (&)[N] buffer)

Generates N 32- or 64-bit quantities (depending on the type UInt) and stores them in the buffer array. This is the most efficient way to obtain more than one quantity at a time, as it reduces the number of calls into the Random Number Generator source.

For example, to fill generate two 32-bit quantities, one may write:

    quint32 array[2];
    QRandomGenerator::global()->fillRange(array);

It would have also been possible to make one call to generate64() and then split the two halves of the 64-bit value.

See also generate().

template <typename UInt, QRandomGenerator::IfValidUInt<UInt> = true> void QRandomGenerator::fillRange(UInt *buffer, qsizetype count)

Generates count 32- or 64-bit quantities (depending on the type UInt) and stores them in the buffer pointed by buffer. This is the most efficient way to obtain more than one quantity at a time, as it reduces the number of calls into the Random Number Generator source.

For example, to fill a list of 16 entries with random values, one may write:

    QList<quint32> list;
    list.resize(16);
    QRandomGenerator::global()->fillRange(list.data(), list.size());

See also generate().

quint64 QRandomGenerator::generate64()

Generates a 64-bit random quantity and returns it.

See also operator()() and generate().

quint32 QRandomGenerator::generate()

Generates a 32-bit random quantity and returns it.

See also operator()() and generate64().

template <typename ForwardIterator> void QRandomGenerator::generate(ForwardIterator begin, ForwardIterator end)

Generates 32-bit quantities and stores them in the range between begin and end. This function is equivalent to (and is implemented as):

    std::generate(begin, end, [this]() { return generate(); });

This function complies with the requirements for the function std::seed_seq::generate, which requires unsigned 32-bit integer values.

Note that if the [begin, end) range refers to an area that can store more than 32 bits per element, the elements will still be initialized with only 32 bits of data. Any other bits will be zero. To fill the range with 64 bit quantities, one can write:

    std::generate(begin, end, []() { return QRandomGenerator::global()->generate64(); });

If the range refers to contiguous memory (such as an array or the data from a QList), the fillRange() function may be used too.

See also fillRange().

double QRandomGenerator::generateDouble()

Generates one random qreal in the canonical range [0, 1) (that is, inclusive of zero and exclusive of 1).

This function is equivalent to:

    QRandomGenerator64 rd;
    return std::generate_canonical<qreal, std::numeric_limits<qreal>::digits>(rd);

The same may also be obtained by using std::uniform_real_distribution with parameters 0 and 1.

See also generate(), generate64(), and bounded().

[static] QRandomGenerator *QRandomGenerator::global()

Returns a pointer to a shared QRandomGenerator that was seeded using securelySeeded(). This function should be used to create random data without the expensive creation of a securely-seeded QRandomGenerator for a specific use or storing the rather large QRandomGenerator object.

For example, the following creates a random RGB color:

    return QColor::fromRgb(QRandomGenerator::global()->generate());

Accesses to this object are thread-safe and it may therefore be used in any thread without locks. The object may also be copied and the sequence produced by the copy will be the same as the shared object will produce. Note, however, that if there are other threads accessing the global object, those threads may obtain samples at unpredictable intervals.

Note: This function is thread-safe.

See also securelySeeded() and system().

[static constexpr] QRandomGenerator::result_type QRandomGenerator::max()

Returns the maximum value that QRandomGenerator may ever generate. That is, std::numeric_limits<result_type>::max().

See also min() and QRandomGenerator64::max().

[static constexpr] QRandomGenerator::result_type QRandomGenerator::min()

Returns the minimum value that QRandomGenerator may ever generate. That is, 0.

See also max() and QRandomGenerator64::min().

[static] QRandomGenerator QRandomGenerator::securelySeeded()

Returns a new QRandomGenerator object that was securely seeded with QRandomGenerator::system(). This function will obtain the ideal seed size for the algorithm that QRandomGenerator uses and is therefore the recommended way for creating a new QRandomGenerator object that will be kept for some time.

Given the amount of data required to securely seed the deterministic engine, this function is somewhat expensive and should not be used for short-term uses of QRandomGenerator (using it to generate fewer than 2600 bytes of random data is effectively a waste of resources). If the use doesn't require that much data, consider using QRandomGenerator::global() and not storing a QRandomGenerator object instead.

See also global() and system().

void QRandomGenerator::seed(quint32 seed = 1)

Reseeds this object using the value seed as the seed.

[noexcept] void QRandomGenerator::seed(std::seed_seq &seed)

This is an overloaded function.

Reseeds this object using the seed sequence seed as the seed.

[static] QRandomGenerator *QRandomGenerator::system()

Returns a pointer to a shared QRandomGenerator that always uses the facilities provided by the operating system to generate random numbers. The system facilities are considered to be cryptographically safe on at least the following operating systems: Apple OSes (Darwin), BSDs, Linux, Windows. That may also be the case on other operating systems.

They are also possibly backed by a true hardware random number generator. For that reason, the QRandomGenerator returned by this function should not be used for bulk data generation. Instead, use it to seed QRandomGenerator or a random engine from the <random> header.

The object returned by this function is thread-safe and may be used in any thread without locks. It may also be copied and the resulting QRandomGenerator will also access the operating system facilities, but they will not generate the same sequence.

Note: This function is thread-safe.

See also securelySeeded() and global().

QRandomGenerator::result_type QRandomGenerator::operator()()

Generates a 32-bit random quantity and returns it.

See also generate() and generate64().

Related Non-Members

bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)

Returns true if the two engines rng1 and rng2 are at different states or if one of them is reading from the operating system facilities and the other is not, false otherwise.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.