C ++ 0x中的随机数 [英] Random numbers in C++0x
问题描述
新的C ++ 11标准有一整章专门用于随机数生成器。但是我如何执行最简单,最常见的任务,过去这样编码,但不求助于标准的C库:
srand int)time(0));
int i = rand();
有合理的默认值为随机数引擎,分布和种子,可以使用
b p $ p>
std :: default_random_engine e((unsigned int)time(0));
int i = e();
default_random_engine
的质量取决于实现。您也可以使用 std :: min_rand0
或 std :: min_rand
。
可能一个更好的种子随机引擎的方法是使用实现中的随机数,而不是使用 time
。
Eg
std :: random_device rd;
std :: default_random_engine e(rd());
The new C++11 Standard has a whole chapter dedicated to random number generators. But how do I perform the simplest, most common task that used to be coded like this, but without resorting to the standard C library:
srand((unsigned int)time(0)); int i = rand();
Are there reasonable defaults for random-number engines, distributions, and seeds that one could use out of the box?
You should be able to do something like:
std::default_random_engine e((unsigned int)time(0));
int i = e();
The quality of the default_random_engine
is implementation dependent. You could also use std::min_rand0
or std::min_rand
.
Probably a better way to seed a random engine is with as true a random number as is available from the implementation rather than use time
.
E.g.
std::random_device rd;
std::default_random_engine e( rd() );
这篇关于C ++ 0x中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!