boost创建随机数

在C++中,利用boost库中的类创建随机数

以一个在[-10,10)上的均匀分布为例

  • 使用的头文件:
    boost/random.hpp
  • 步骤:
  1. 创建随机数的生成器
  2. 创建随机数的分布函数
  3. 装配生成器与分布函数,生成变量生成器
  • 代码及注释如下:
#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值