QRandomGenerator¶
The
QRandomGenerator
class allows one to obtain random values from a highquality Random Number Generator. More…
Inherited by: QRandomGenerator64
New in version 5.10.
Detailed Description¶
QRandomGenerator
may be used to generate random values from a highquality random number generator. Like the C++ random engines,QRandomGenerator
can be seeded with userprovided 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.
securelySeeded()
can be used to create aQRandomGenerator
that is securely seeded withsystem()
, meaning that the sequence of numbers it generates cannot be easily predicted. Additionally,global()
returns a global instance ofQRandomGenerator
that Qt will ensure to be securely seeded. This object is threadsafe, may be shared for most uses, and is always seeded fromsystem()
system()
may be used to access the system’s cryptographicallysafe random generator. On Unix systems, it’s equivalent to reading from/dev/urandom
or thegetrandom()
orgetentropy()
system calls.The class can generate 32bit or 64bit quantities, or fill an array of those. The most common way of generating new values is to call the
generate()
,generate64()
orfillRange()
functions. One would use it as:quint32 value = QRandomGenerator::global()>generate();Additionally, it provides a floatingpoint 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 32bit 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.
global()
, like all generators created bysecurelySeeded()
, is always seeded fromsystem()
, 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 cryptographicallysecure or true random data are advised to use a regularQRandomGenerator
instead ofsystem()
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);
Systemwide random number generator¶
system()
may be used to access the systemwide random number generator, which is cryptographicallysafe 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 implementationdefined. Therefore,system()
should not be used for highfrequency 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,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.system()
can be used to seed those.
Fallback quality¶
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 pseudorandom engine for a time. Under no circumstances willsystem()
block, waiting for more entropy to be collected.The following operating systems guarantee that the results from their randomgeneration API will be of at least cryptographicallysafe 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),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 noncryptographic quality generators are advised to check their operating system documentation or restrict their deployment to one of the above.
Reentrancy and threadsafety¶
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
global()
andsystem()
: those objects are threadsafe and may be used by any thread without external locking. Note that threadsafety 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 sequencelike class besides std::seed_seq itself;
QRandomGenerator
is not comparable (but is copyable) or streamable tostd::ostream
or fromstd::istream
.
QRandomGenerator
is also compatible with the uniform distribution classesstd::uniform_int_distribution
andstd:uniform_real_distribution
, as well as the free functionstd::generate_canonical
. For example, the following code may be used to generate a floatingpoint number in the range [1, 2.5):std::uniform_real_distribution dist(1, 2.5); return dist(*QRandomGenerator::global());See also
QRandomGenerator64
qrand()

class
QRandomGenerator
(other)¶ QRandomGenerator(begin, end)
QRandomGenerator(seedBuffer, len)
QRandomGenerator([seedValue=1])
 param begin
quint32
 param seedValue
quint32
 param other
 param len
long long
 param seedBuffer
quint32
 param end
quint32
This is an overloaded function.
Initializes this
QRandomGenerator
object with the values found in the range frombegin
toend
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
Initializes this
QRandomGenerator
object with the valueseedValue
as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.See also

PySide2.QtCore.QRandomGenerator.
bounded
(highest)¶  Parameters
highest –
double
 Return type
double
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

PySide2.QtCore.QRandomGenerator.
bounded
(highest)  Parameters
highest –
int
 Return type
int
This is an overloaded function.
Generates one random 32bit 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 32bit range of int. Instead, use
generate()
and cast to int.See also

PySide2.QtCore.QRandomGenerator.
bounded
(lowest, highest)  Parameters
lowest –
int
highest –
int
 Return type
int
This is an overloaded function.
Generates one random 32bit quantity in the range between
lowest
(inclusive) andhighest
(exclusive), both of which may be negative, buthighest
must be greater thanlowest
.Note that this function cannot be used to obtain values in the full 32bit range of int. Instead, use
generate()
and cast to int.See also

PySide2.QtCore.QRandomGenerator.
bounded
(highest)  Parameters
highest –
quint32
 Return type
quint32
This is an overloaded function.
Generates one random 32bit quantity in the range between 0 (inclusive) and
highest
(exclusive). The same result may also be obtained by usingstd::uniform_int_distribution
` <http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution>`_ with parameters 0 andhighest  1
. That class can also be used to obtain quantities larger than 32 bits.For example, to obtain a value between 0 and 255 (inclusive), one would write:
quint32 v = QRandomGenerator::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 32bit range of quint32. Instead, use
generate()
.See also

PySide2.QtCore.QRandomGenerator.
bounded
(lowest, highest)  Parameters
lowest –
quint32
highest –
quint32
 Return type
quint32
This is an overloaded function.
Generates one random 32bit quantity in the range between
lowest
(inclusive) andhighest
(exclusive). Thehighest
parameter must be greater thanlowest
.The same result may also be obtained by using
std::uniform_int_distribution
` <http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution>`_ with parameterslowest
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::bounded(1000, 2000);
Note that this function cannot be used to obtain values in the full 32bit range of quint32. Instead, use
generate()
.See also

PySide2.QtCore.QRandomGenerator.
discard
(z)¶  Parameters
z – long
Discards the next
z
entries from the sequence. This method is equivalent to callinggenerate()
z
times and discarding the result, as in:while (z) generator.generate();

PySide2.QtCore.QRandomGenerator.
generate
()¶  Return type
quint32
Generates a 32bit random quantity and returns it.
See also
operator()()
generate64()

PySide2.QtCore.QRandomGenerator.
generate
(begin, end)  Parameters
begin –
quint32
end –
quint32

PySide2.QtCore.QRandomGenerator.
generate64
()¶  Return type
quint64
Generates a 64bit random quantity and returns it.
See also
operator()()
generate()

PySide2.QtCore.QRandomGenerator.
generateDouble
()¶  Return type
double
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
` <http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution>`_ with parameters 0 and 1.See also

static
PySide2.QtCore.QRandomGenerator.
global_
()¶  Return type
Returns a pointer to a shared
QRandomGenerator
that was seeded usingsecurelySeeded()
. This function should be used to create random data without the expensive creation of a securelyseededQRandomGenerator
for a specific use or storing the rather largeQRandomGenerator
object.For example, the following creates a random RGB color:
return QColor::fromRgb(QRandomGenerator::global()>generate());
Accesses to this object are threadsafe 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.
See also

static
PySide2.QtCore.QRandomGenerator.
max
()¶  Return type
long
Returns the maximum value that
QRandomGenerator
may ever generate. That is,std::numeric_limits<result_type>::max()
.See also
min()
max()

static
PySide2.QtCore.QRandomGenerator.
min
()¶  Return type
long
Returns the minimum value that
QRandomGenerator
may ever generate. That is, 0.See also
max()
min()

static
PySide2.QtCore.QRandomGenerator.
securelySeeded
()¶  Return type
Returns a new
QRandomGenerator
object that was securely seeded withsystem()
. This function will obtain the ideal seed size for the algorithm thatQRandomGenerator
uses and is therefore the recommended way for creating a newQRandomGenerator
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 shortterm 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 usingglobal()
and not storing aQRandomGenerator
object instead.See also
global()
system()

PySide2.QtCore.QRandomGenerator.
seed
([s=1])¶  Parameters
s –
quint32
Reseeds this object using the value
seed
as the seed.

static
PySide2.QtCore.QRandomGenerator.
system
()¶  Return type
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 seedQRandomGenerator
or a random engine from the <random> header.The object returned by this function is threadsafe 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.See also
securelySeeded()
global()
© 2019 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.