C++ 11 在头文件 #include 中定义了随机数库,也可以使用 C 中生成随机数的方法。
C 语言中使用 rand() 函数产生 0 ~ RAND_MAX 范围内均匀分布到整数,其中 RAND_MAX 是和系统相关的一个固定值。
1 2 3 4 5 |
#include<stdlib.h> #include<time.h>
srand(time(nullptr));//设置随机数种子 rand();//产生一个随机数 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{//产生 [0,b) 范围内到随机数 int randoxNumber = rand() % b ; } {//产生 [a,b) 范围内到随机数 int randoxNumber = a + rand() % ( b -a ) ; } {//产生 [a,b] 范围内到随机数 int randoxNumber = a + rand() % ( b -a +1 ) ; } {//产生 [0,1] 范围内到随机小数 double randoxNumber =rand() / RAND_MAX } {//产生 [0,1) 范围内到随机小数 double randoxNumber =rand() / ( RAND_MAX +1 ) } |
C++ 11 在头文件 #include 中定义了随机数库,包括随机数生成器和随机数分布器。
①.概述
随机数生成器用来使用指定的种子产生一个随机数。
②.random_device
random_device 是标准库提供到一个非确定性随机数生成器,使用硬件作为随机数来源,故其调用代价较高,一般用来产生随机数种子。
1 2 3 4 5 |
random_device rd; for (int i = 0; i < 10; ++i) { cout << rd() << endl; } |
③.default_random_engine
default_random_engine 是标准库提供的默认随机数生成器,其实现和编译器有关。
1 2 3 4 5 6 7 |
random_device rd;
default_random_engine r_eng(rd()); for (int i = 0; i < 10; ++i) { cout << r_eng() << endl; } |
④.minstd_rand
minstd_rand 是标准库提供的采用线性同余算法的伪随机数生成器。
1 2 3 4 5 6 7 |
random_device rd;
minstd_rand r_eng(rd()); for (int i = 0; i < 10; ++i) { cout << r_eng() << endl; } |
⑤.mt19937
mt19937 是标准库提供的采用梅森旋转算法的伪随机数生成器,可以快速产生高质量到随机数。
1 2 3 4 5 6 7 |
random_device rd;
mt19937 r_eng(rd()); for (int i = 0; i < 10; ++i) { cout << r_eng() << endl; } |
⑥.ranlux24_base
ranlux24_base 是标准库提供的采用带进位减法的伪随机数生成器。
1 2 3 4 5 6 7 |
random_device rd;
ranlux24_base r_eng(rd()); for (int i = 0; i < 10; ++i) { cout << r_eng() << endl; } |
①.概述
随机数分布器用于限定生成随机数的范围及分布类型。
②.uniform_int_distribution
uniform_int_distribution 用于生成指定范围的均匀分布的整数。
1 2 3 4 5 6 7 8 |
random_device rd;//用于生成随机数种子 mt19937 r_eng(rd());//随机数生成器 uniform_int_distribution<int> dis(1, 100);//随机数分布器 闭区间
for (int i = 0; i < 10; ++i) { cout << dis(r_eng) << endl; } |
③.uniform_real_distribution
uniform_real_distribution 用于生成指定范围的均匀分布的浮点数。
1 2 3 4 5 6 7 8 |
random_device rd;//用于生成随机数种子 mt19937 r_eng(rd());//随机数生成器 uniform_real_distribution<double> dis(1, 100);//随机数分布器 闭区间
for (int i = 0; i < 10; ++i) { cout << dis(r_eng) << endl; } |
④.normal_distribution
normal_distribution 用于生成指定均值和方差的正态分布的浮点数。
1 2 3 4 5 6 7 8 |
random_device rd;//用于生成随机数种子 mt19937 r_eng(rd());//随机数生成器 normal_distribution <> dis(4, 1.5);//随机数分布器,均值、方差
for (int i = 0; i < 10; ++i) { cout << dis(r_eng) << endl; } |
⑤.bernoulli_distribution
bernoulli_distribution 用于生成二项分布到布尔值,可以指定 true 的概率。
1 2 3 4 5 6 7 8 |
random_device rd;//用于生成随机数种子 mt19937 r_eng(rd());//随机数生成器 bernoulli_distribution dis( 0.6);//随机数分布器,生成 1 的概率是 0.6
for (int i = 0; i < 10; ++i) { cout << dis(r_eng) << endl; } |
Qt 中生成随机数的方法和 C 语言中差不多,对应到函数为 qsrand() 、qrand()。使用使需要包含头文件 #include 。
1 2 3 4 5 6 7 |
auto seed = QDateTime::currentDateTime().toMSecsSinceEpoch();
qsrand(seed); for (int i = 0; i < 10; ++i) { qDebug() << qrand() % 10;// 0 - 9 范围 } |