在C++中,利用boost库中的类创建随机数
以一个在[-10,10)上的均匀分布为例
- 使用的头文件:
boost/random.hpp
- 步骤:
- 创建随机数的生成器
- 创建随机数的分布函数
- 装配生成器与分布函数,生成变量生成器
- 代码及注释如下:
#include <iostream>
#include <boost/random.hpp>
using std::cout;
using std::endl;
using boost::mt19937;
using boost::random::uniform_real_distribution;
using boost::variate_generator;
int main(){
// 1. 创建随机数的生成器
mt19937 randomGenerator;
// 2. 创建随机数的分布函数
uniform_real_distribution<double> urd(-10.0, 10.0);
// 3. 装配生成器与分布函数,生成变量生成器
variate_generator<mt19937, uniform_real_distribution<double> > vg(randomGenerator, urd);
// 输出验证:
for(int i = 0; i < 20; i++){
cout << vg() << " ";
}
cout << endl;
}
- 输出:
6.29447 -7.29046 8.11584 6.70017 -7.46026 9.37736 8.26752 -5.57932 2.64718 -3.83666 -8.04919 0.944412 -4.43004 -6.23236 0.93763 9.85763 9.15014 9.92923 9.29777 9.3539
备注: 在我的机器上,对代码不加修改地重复编译并运行多次,这20个随机数不改变。
参考链接:
https://www.boost.org/doc/libs/1_57_0/boost/random/uniform_real_distribution.hpp
https://www.cnblogs.com/wjgaas/p/3848979.html