Boost logo

Boost :

From: nbecker_at_[hidden]
Date: 2001-04-03 14:30:52


Here is a revised version of the PN sequence generator. I hope this
is better than the previous one:

#ifndef pnseq_generator_H
#define pnseq_generator_H

#include <boost/random.hpp>
#include <iostream>

namespace boost
{
  namespace random
  {

    template < class RandomNumberGenerator >
    class pnseq_generator
    {

    public:
      typedef pnseq_generator<RandomNumberGenerator> self_type;
      typedef RandomNumberGenerator base_type;
      typedef bool result_type;

      BOOST_STATIC_CONSTANT( bool, has_fixed_range = true );
      BOOST_STATIC_CONSTANT( result_type, min_value = false );
      BOOST_STATIC_CONSTANT( result_type, max_value = true );

      result_type min() const
      { return min_value; }
      result_type max() const
      { return max_value; }

      explicit pnseq_generator (base_type & rng)
        : rng_( rng ), count_()
      { init(); }

      template < typename T >
      void seed( T s )
      { rng_.seed( s ); init(); }

      result_type operator()()
      {
        bool const bit = cache_ & 1;
        cache_ >>= 1;
        if ( --count_ <= 0 )
          init();
        return bit;
      }

      bool validation( result_type x ) const
      { return valid == x; }

      friend bool operator ==( self_type const &x, self_type const &y )
      {
        return x.rng_ == y.rng_ && x.cache_ == y.cache_
          && x.count_ == y.count_;
      }
      friend bool operator !=( self_type const &x, self_type const &y )
      { return !(x == y); }

    private:
      typedef typename base_type::result_type cache_type;

      void init()
      {
        cache_ = rng_();
        count_ = std::numeric_limits<cache_type>::digits;
      }

      base_type& rng_;
      cache_type cache_;
      int count_;

    }; // boost::random::pnseq_generator

  } // random
} // boost

#endif

--------------------
#include <above header>
#include <algorithm>

// demonstrate that we are sharing a rng
main () {
  boost::mt19937 rng;
  boost::random::pnseq_generator<boost::mt19937> pn (rng);
  boost::random::pnseq_generator<boost::mt19937> pn2 (rng);

  vector<double> x (10);
  vector<double> x2 (10);

  generate< vector<double>::iterator, typeof (pn)& >
    (x.begin(), x.end(), pn);
                                                                               
  generate< vector<double>::iterator, typeof (pn)& >
    (x2.begin(), x2.end(), pn2);

  assert (x != x2);

}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk