Advertisement
kokorins

chen_method

Nov 6th, 2012
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. //chen.h
  2. #ifndef CHEN_H_
  3. #define CHEN_H_
  4. #include <vector>
  5. #include <boost/random.hpp>
  6. /// \file chen.h
  7. /// \mainpage Chen discrete finite distribution generator algorithm
  8. namespace chen
  9. {
  10. class Chen {
  11. public:
  12.   explicit Chen(const std::vector<double>& probs);
  13.   /**
  14.    * Generates new pseudo-random value
  15.    * \return is 0..n-1
  16.    */
  17.   size_t next();
  18.   /**
  19.    * Return the already created value
  20.    * \sa next()
  21.    */
  22.   size_t lookup()const;
  23.   void setProbs(const std::vector<double>& p);
  24.   void setSeed(int seed) const;
  25. private:
  26.   size_t _cur_value;
  27.   std::vector<double> _p;
  28.   std::vector<double> _s;
  29.   size_t _param;
  30.   std::vector<size_t> _r;
  31.   boost::uniform_01<> _alpha;
  32.   mutable boost::minstd_rand _gen;
  33. };
  34. }//namespace chen
  35. #endif
  36. //chen.cpp
  37. #include "chen.h"
  38. #include <cmath>
  39. #include <numeric>
  40.  
  41. namespace chen {
  42. Chen::Chen(const std::vector<double>&probs): _param(probs.size()+1)
  43. {
  44.   setProbs(probs);
  45.   next();
  46. }
  47.  
  48. size_t Chen::next()
  49. {
  50.   double alpha = _alpha(_gen);
  51.   size_t j=(size_t)std::floor(_param*alpha);
  52.   size_t i=_r[j];
  53.   while(alpha>=_s[i])
  54.     ++i;
  55.   _cur_value=i;
  56.   return _cur_value;
  57. }
  58.  
  59. void Chen::setProbs(const std::vector<double>&probs)
  60. {
  61.   _p=probs;
  62.   _s=_p;
  63.   std::partial_sum(_s.begin(),_s.end(),_s.begin());//s_i=sum(p_1+...p_i)
  64.   size_t i = 0;
  65.   double t=0;
  66.   _param = probs.size()+1;
  67.   _r.resize(_param);
  68.   double revparam=1./_param;
  69.   for(size_t j=0; j<_param; ++j) {
  70.     while(_s[i]<=t)
  71.       ++i;
  72.     _r[j] = i;
  73.     t += revparam;
  74.   }
  75. }
  76.  
  77. void Chen::setSeed(int seed)const
  78. {
  79.   _gen.seed(seed);
  80. }
  81.  
  82. size_t Chen::lookup() const
  83. {
  84.   return _cur_value;
  85. }
  86. } //namespace chen
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement