首页 > 代码库 > boost random的应用

boost random的应用

最近忙着新项目的框架搭建,实在是太忙了···

boost有很多随机引擎就不一一介绍了,

一般常用mt19937内存效率质量折中,

rand48算法效率最高内存占用小质量一般

 

 1 #pragma once 2 #include <boost/random.hpp> 3 #include <enable_singleton.h> 4 #include <boost/thread.hpp> 5  6 template<class T = boost::rand48> 7 class enable_random 8 { 9 public:10     enable_random(int seed)11         :m_rand(seed)12     {13 14     }15 16     int rand_100()17     {18         static boost::uniform_int<> ui(0,100);19         return ui(m_rand);20     }21 22     int rand_1w()23     {24         static boost::uniform_int<> ui(0,10000);25         return ui(m_rand);26     }27 28     int rand_int(int min, int max)29     {30         boost::uniform_int<> ui(min,max);31         return ui(m_rand);32     }33 34     double rand_01()35     {36         static boost::uniform_01<> ui;37         return ui(m_rand);38     }39 40     double rand_double(double min, double max)41     {42         boost::uniform_real<> ui(min, max);43         return ui(m_rand);44     }45 46 private:47     T m_rand;48 };49 50 //全局随机51 class global_random52     :public enable_singleton<global_random>53 {54 public:55 56     int rand_100()57     {58         return get_gen().rand_100();59     }60 61     int rand_1w()62     {        63         return get_gen().rand_1w();64     }65 66     int rand_int(int min, int max)67     {68         return get_gen().rand_int(min, max);69     }70 71     double rand_01()72     {73         return get_gen().rand_01();74     }75 76     double rand_double(double min, double max)77     {78         return get_gen().rand_double(min, max);79     }80 81 private:82     boost::thread_specific_ptr<enable_random<boost::mt19937>> m_rand;83 84     enable_random<boost::mt19937>& get_gen()85     {86         enable_random<boost::mt19937> *pRng = m_rand.get();87         if (pRng) return *pRng;88 89         m_rand.reset(new enable_random<boost::mt19937>(std::time(nullptr)));90         return *m_rand.get();91     }92 };
enable_random.h

 

boost random的应用