首页 > 学院 > 开发设计 > 正文

基于Boost库生成随机数

2019-11-08 02:54:24
字体:
来源:转载
供稿:网友
#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 0int 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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表