1. random_device
标准库提供了一个非确定性随机数生成设备.在Linux的实现中,是读取/dev/urandom设备;Windows的实现居然是用rand_s,在这里强烈谴责一下.
random_device提供()操作符,用来返回一个min()到max()之间的一个数字.如果是Linux(Unix Like或者Unix)下,都可以使用这个来产生高质量的随机数,可以理解为真随机数
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
for(int n=0; n<20000; ++n)
std::cout << rd() << std::endl;
return 0;
}
2. random number engine
标准把随机数抽象成随机数引擎和分布两部分
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 mt(rd());
for(int n = 0; n < 10; n++)
std::cout << mt() << std::endl;
return 0;
}
3. random number distributions
//平均分布
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for(int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
//正太分布
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <cmath>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> d(5,2);
std::map<int, int> hist;
for(int n=0; n<10000; ++n){
++hist[std::round(d(gen))];
}
for(auto p : hist) {
std::cout << std::fixed << std::setprecision(1) << std::setw(2)
<< p.first << ' ' << std::string(p.second/200, '*')
<< '\n';
}
}
//补充函数
#if defined(_WIN32)
namespace std
{
int round(double d)
{
return static_cast<int>(d + 0.5);
}
}
#endif