View source code
Display the source code in std/random.d from which thispage was generated on github.
Report a bug
If you spot a problem with this page, click here to create aBugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinglocal clone.

Function std.random.unpredictableSeed

A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run.

uint unpredictableSeed() nothrow @property @nogc @trusted;
alias unpredictableSeed(UIntType) = unpredictableSeed;

This function utilizes the system cryptographically-secure pseudo-random number generator (CSPRNG) or pseudo-random number generator (PRNG) where available and implemented (currently arc4random on applicable BSD systems, getrandom on Linux or BCryptGenRandom on Windows) to generate “high quality” pseudo-random numbers – if possible. As a consequence, calling it may block under certain circumstances (typically during early boot when the system's entropy pool has not yet been initialized).

On x86 CPU models which support the RDRAND instruction, that will be used when no more specialized randomness source is implemented.

In the future, further platform-specific PRNGs may be incorporated.

Function unpredictableSeed

Alias unpredictableSeed

Warning

This function must not be used for cryptographic purposes. Despite being implemented for certain targets, there are no guarantees that it sources its randomness from a CSPRNG. The implementation also includes a fallback option that provides very little randomness and is used when no better source of randomness is available or integrated on the target system. As written earlier, this function only aims to provide randomness for seeding ordinary (non-cryptographic) PRNG engines.

Returns

A single unsigned integer seed value, different on each successive call

Note

In general periodically 'reseeding' a PRNG does not improve its quality and in some cases may harm it. For an extreme example the Mersenne Twister has 2 ^^ 19937 - 1 distinct states but after seed(uint) is called it can only be in one of 2 ^^ 32 distinct states regardless of how excellent the source of entropy is.

Example

auto rnd = Random(unpredictableSeed);
auto n = rnd.front;
static assert(is(typeof(n) == uint));

Authors

Andrei Alexandrescu Masahiro Nakagawa (Xorshift random generator) Joseph Rushton Wakeling (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from mir-random)

License

Boost License 1.0.