随机双C ++ 11 [英] Random double C++11
问题描述
下面的代码显示了如何在C ++ 11中随机加倍.每次在此解决方案中,当我运行此程序时,结果都是相同的-我不知道为什么?每次运行程序时如何更改它以获得不同的解决方案?
The code below show how to random double in C++11. In this solution each time, when I run this program the result are the same - I don't know why? How to change it to get different solution in every time when I run the program?
#include <random>
int main(int argc, char **argv)
{
double lower_bound = 0.;
double upper_bound = 1.;
std::uniform_real_distribution<double> unif(lower_bound, upper_bound);
std::default_random_engine re;
double a_random_double = unif(re);
cout << a_random_double << endl;
return 0;
}
//compilation: "g++ -std=c++0x program_name.cpp -o program_name"
推荐答案
在生成样本之前,您需要给随机数生成器添加种子.构造default_random_engine
实例时,您可以执行此操作.例如:
You need to seed the random number generator before you generate samples. You do this when you construct the default_random_engine
instance. For example:
std::random_device rd;
std::default_random_engine re(rd());
如果希望对所使用的生成器有更多的说明,则应指定一个,而不要依赖库实现者对default_random_engine
的选择.可用的选项在此处列出: http://en.cppreference.com/w/cpp/numeric/random#Predefined_random_number_generators
If you wish to be more prescriptive about the generator you use then you should specify one rather than relying on the library implementor's choice for default_random_engine
. The available choices are listed here: http://en.cppreference.com/w/cpp/numeric/random#Predefined_random_number_generators
还请注意,某些实现并未为random_device
使用非确定性源.如果您遇到这样的实现,则需要找到种子的替代来源.
Also beware that some implementations do not use a non-deterministic source for random_device
. If you are faced with such an implementation, you'll need to find an alternative source for your seed.
这篇关于随机双C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!