std :: default_random_engine生成介于0.0和1.0之间的值 [英] std::default_random_engine generate values between 0.0 and 1.0
本文介绍了std :: default_random_engine生成介于0.0和1.0之间的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够生成0.0到1.0之间的随机值
I want to be able to generate random values between 0.0 and 1.0
我尝试使用
std::default_random_engine generator;
std::uniform_real_distribution<float> distribution(0.0, 1.0);
float myrand = distribution(generator);
在循环中生成随机值始终为我提供以下值:
Generating random value in a loop gives me always these values:
0.000022
0.085032
0.601353
0.891611
0.967956
0.189690
0.514976
0.398008
0.262906
0.743512
0.089548
我该怎么做才能真正获得随机值?
如果我总是得到相同的东西,似乎不是那么随机。
What can I do to really get random values? Doesn't seem that random if I always get the same ones.
推荐答案
// 1-st variant: using time() function for seed random distribution
std::default_random_engine generator(time(0));
std::uniform_real_distribution<double> distribution(first, last);
return distribution(generator);
如果打开多个程序,并且使用相同的随机数生成器,它们将全部输出相同的结果,因为它们具有与时间相同的种子值。
If open multiple programs, with the same random number generator they will all output the same results, because they have the same value of seed which is time.
此问题通过使用随机设备在以下代码中解决:
This issue solved by using random device, in the below code:
// 2-nd variant:
std::uniform_real_distribution<double> distribution(first, last);
std::random_device rd;
std::default_random_engine generator(rd());
return distribution(generator);
这篇关于std :: default_random_engine生成介于0.0和1.0之间的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文