基于Boost库生成随机数

#include <boost/random.hpp>
#include <ctime>
#include <iostream>
#include <fstream>
using namespace std;

// 生成正态分布随机数
double sampleNormal( double mean, double sigma )
{
    // 建立Mersenne twister随机数生成器
    // 使用Unix时间设定seed
    static boost::mt19937 rng( static_cast< unsigned >( std::time( 0 ) ) );

    // 选择高斯随机分布
    boost::normal_distribution< double > norm_dist( mean, sigma );

    // 使用function的形式,生成随机数产生器
    boost::variate_generator< boost::mt19937&, boost::normal_distribution< double > > normal_sampler( rng, norm_dist );
    return normal_sampler( );
}

// 生成一定范围内的随机整数
// 值域是[start, end]
int sampleUniformInt( int start, int end )
{
    static boost::mt19937 rng( static_cast< unsigned >( std::time( 0 ) ) );
    boost::uniform_int< > uni_dist( start, end );

    return uni_dist( rng );
}

// 生成一定范围内的随机实数
double sampleUniformDouble( double start, double end )
{
    static boost::mt19937 rng( static_cast< unsigned >( std::time( 0 ) ) );
    boost::uniform_real< > uni_dist( start, end );
    return uni_dist( rng );
}

#define DEMO_NORMAL_DIST 1
#define DEMO_UNI_DIST_INT 0
#define DEMO_UNI_DIST_DOUBLE 0
int main( )
{
    // 正态分布样本输出
#if DEMO_NORMAL_DIST
    ofstream o_normal_distribution_file( "normal_distribution.txt" );
#endif
#if DEMO_UNI_DIST_INT
    ofstream o_uni_distribution_int_file( "uni_distribution_int.txt" );
#endif
#if DEMO_UNI_DIST_DOUBLE
    ofstream o_uni_distribution_double_file( "uni_distribution_double.txt" );
#endif
    while ( 1 )
    {
        // 正态分布测试
#if DEMO_NORMAL_DIST
        cout << sampleNormal( 10, 0.1 ) << endl;
        o_normal_distribution_file << sampleNormal( 10, 0.1 ) << endl;
#endif
        // 整数均匀分布测试
#if DEMO_UNI_DIST_INT
        cout << sampleUniformInt( 0, 9 ) << endl;
        o_uni_distribution_int_file << sampleUniformInt( 0, 9 ) << endl;
#endif
        // 实数均匀分布测试
#if DEMO_UNI_DIST_DOUBLE
        cout << sampleUniformDouble( 0, 1 ) << endl;
        o_uni_distribution_double_file << sampleUniformDouble( 0, 1 ) << endl;
#endif
    }
    return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值