基于Boost庫生成隨機數
2019-11-08 02:54:24
供稿:網友
#include <boost/random.hpp>#include <ctime>#include <iostream>#include <fstream>using namespace std;// 生成正態(tài)分布隨機數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( ){ // 正態(tài)分布樣本輸出#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 ) { // 正態(tài)分布測試#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;}