void TestDefaultRandom() {
std::default_random_engine engine(time(NULL));
std::uniform_int_distribution distribution(1, 10);
std::cout << distribution(engine)
<< std::endl; //生成1-10(包含1、10)的随机数
}
void TestLiner_random() {
std::linear_congruential_engine<unsigned int, 3, 2, 10> linear_engine;
linear_engine.seed(2021);
//计算公式 (_Ax* seed+_Cx) mod _Mx;
//所以随机数取决于 seed
std::cout << "TestLiner_random:" << linear_engine() << std::endl;
}
//生成真随机数,但是不一定所有的系统支持,在不支持的系统上调用构造或者operator 会产生异常,
//所以建议如果真的用,需要提供处理异常的代码。
//所以建议使用伪随机数
void TestTrueRandom() {
try
{
std::random_device rd;
std::cout << "TestTrueRandom:" << rd() << std::endl;
}
catch (const std::exception&)
{
std::cout << "catch exception" << std::endl;
}
}
//线型同余求随机数的两个模板实例:
//
void TestMinstd_Random(){
std::minstd_rand rd; //默认随机种子是1
std::cout << "TestMinstd_Random:" << rd() << std::endl;
}
void TestMinstd_Random0(){
std::minstd_rand0 rd; //默认随机种子是1
std::cout << "TestMinstd_Random0:" << rd() << std::endl;
}
//相同开销下 std::Minstd_rand 产生的随机数比minstd_rand0 多
//相对复杂的随机数
void TestMt19937() {
std::mt19937 rd(time(NULL));
for (int i = 0; i < 10; i++) {
std::cout << rd() << " ";
}
std::cout << std::endl;
}
void TestMt19937_64() {
std::mt19937_64 rd(time(NULL));
std::uniform_int_distribution distribution(1, 10);
for (int i = 0; i < 10; i++) {
std::cout << distribution(rd) << " ";
}
std::cout << std::endl;
}
c++标准库获取随机数
最新推荐文章于 2024-06-07 15:54:06 发布