The random number library provides classes that generate random
and pseudo-random numbers. These classes include:
Uniform random bit generators (URBGs), which include both random number engines, which are pseudo-random number
generators that generate integer sequences with a uniform distribution, and true random number generators if
available;
Random number distributions (e.g. uniform, normal, or poisson distributions) which convert the output of URBGs
into various statistical distributions
URBGs and distributions are designed to be used together to produce random values. All of the random number engines
may be specifically seeded, serialized, and deserialized for use with repeatable simulators.
1
#include<random>
12
// Usually a high-cost generatorstd::random_devicerd;
1
unsignedintseed=rd();
123
// We recur to a user-defined function to mix other sources// of entropy in the seedseed=mix_seed(seed);
12
// This is the generator we will ultimately usestd::default_random_engineg(seed);
constexpruint32_tfnv(uint32_thash,constchar*pos){return*pos=='\0'?hash:fnv((hash*16777619U)^*pos,pos+1);}unsignedintmix_seed(unsignedintseed){// Mix seed with some cross-platform entropy sources// - Mix the current timeseed^=static_cast<unsignedint>(std::chrono::system_clock::now().time_since_epoch().count());// - Mix an arbitrary compile-time stampconstexpruint32_tcompile_stamp=fnv(2166136261U,__DATE____TIME____FILE__);seed^=static_cast<unsignedint>(compile_stamp);// - Mix an arbitrary heap addressautoheap_addr=std::make_unique<int>(0);seed^=static_cast<unsignedint>(reinterpret_cast<uintptr_t>(heap_addr.get()));// - Mix an arbitrary stack addressseed^=static_cast<unsignedint>(reinterpret_cast<uintptr_t>(&heap_addr));// - Mix an arbitrary fixed number / counterseed^=static_cast<unsignedint>(45);// - Mix an arbitrary function address (the clock function `now`)seed^=static_cast<unsignedint>(reinterpret_cast<uintptr_t>(&std::chrono::system_clock::now));// - Mix the exit function addressseed^=static_cast<unsignedint>(reinterpret_cast<uintptr_t>((void*)&_Exit));// - Mix the random_device generator type hash codeseed^=static_cast<unsignedint>(typeid(std::random_device).hash_code());returnseed;}