在C++11增加了random库,用于生成随机数,非常方便高效,总结如下:
(1)基于均匀分布的随机数
在linux下生成指定区间内均匀分布的随机数:
#include<random>
#include<iostream>
using namespace std;
int main(){
int min = 0;
int max = 10;
random_device rd;
default_random_engine generator(rd());
uniform_int_distribution<int> dist_int(min, max); //生成[min,max]之间的随机整数
int v1 = dist_int(generator);
double a = 0;
double b = 1;
uniform_real_distribution<double> dist_real(a, b);//生成[a,b]之间的随机浮点数
double v2 = dist_real(generator);
}
(2)基于任意概率分布的随机数
#include<random>
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<double> prob{0.8,0.4,0.2,0.1,0.5};
random_device rd;
default_random_engine generator(rd());
discrete_distribution<int> distribution(prob.begin(), prob.end());
int p[prob.size()] = {};
for(int i = 0; i < 10000; i++){
int idx = distribution(generator); //按照概率prob生成0到prob.size()之间的随机整数
++p[idx];
}
for(int i = 0; i < prob.size(); i++){
cout << p[i] << endl;
}
}