拥有seed_seq 的目的是增加生成序列的熵。如果您的系统上有一个 random_device,则使用该随机设备中的多个数字进行初始化可能会做到这一点。在具有伪随机数生成器的系统上,我认为随机性不会增加,即生成的序列熵。
以您的方法为基础:
如果您的系统确实提供了随机设备,那么您可以像这样使用它:
std::random_device r;
// std::seed_seq ssq{r()};
// and then passing it to the engine does the same
default_random_engine eng{r()};
uniform_real_distribution<double> urd(0, 1);
cout << "Uniform [0, 1): " << urd(eng);
如果您的系统没有随机设备,那么您可以使用time(0) 作为随机引擎的种子
default_random_engine eng{static_cast<long unsigned int>(time(0))};
uniform_real_distribution<double> urd(0, 1);
cout << "Uniform [0, 1): " << urd(eng);
如果您有多个随机来源,您实际上可以这样做(例如 2)
std::seed_seq seed{ r1(), r2() };
default_random_engine eng{seed};
uniform_real_distribution<double> urd(0, 1);
cout << "Uniform [0, 1): " << urd(eng);
其中 r1 , r2 是不同的随机设备,例如热噪声或量子源。
当然可以混搭
std::seed_seq seed{ r1(), static_cast<long unsigned int>(time(0)) };
default_random_engine eng{seed};
uniform_real_distribution<double> urd(0, 1);
cout << "Uniform [0, 1): " << urd(eng);
最后,我喜欢使用单行进行初始化:
auto rand = std::bind(std::uniform_real_distribution<double>{0,1},
std::default_random_engine{std::random_device()()});
std::cout << "Uniform [0,1): " << rand();
如果您担心time(0) 具有第二精度,您可以通过使用high_resolution_clock 来克服这个问题,或者通过请求bames23 below 首先指定的纪元以来的时间:
static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())
或者只是玩 CPU 随机性
long unsigned int getseed(int const K)
{
typedef std::chrono::high_resolution_clock hiclock;
auto gett= [](std::chrono::time_point<hiclock> t0)
{
auto tn = hiclock::now();
return static_cast<long unsigned int>(std::chrono::duration_cast<std::chrono::microseconds>(tn-t0).count());
};
long unsigned int diffs[10];
diffs[0] = gett(hiclock::now());
for(int i=1; i!=10; i++)
{
auto last = hiclock::now();
for(int k=K; k!=0; k--)
{
diffs[i]= gett(last);
}
}
return *std::max_element(&diffs[1],&diffs[9]);
}