Saving and restoring the state
Back to Other random distributions. Forward to Programming tips. Up to Contents.

A Random can be copied, saved, and restored in a variety of ways as illustrated here.

  #if HAVE_BOOST_SERIALIZATION
  // With some versions of boost, these includes need to precede the
  // inclusion of RandomLib/Random.hpp
  #include <boost/archive/xml_iarchive.hpp>
  #include <boost/archive/xml_oarchive.hpp>
  #endif

  #include "RandomLib/Random.hpp"

  unsigned long l = 0;
  double d = 0;
  bool b = false;
  RandomLib::Random r;
  std::cout << "Seed set to: " << r.SeedString() << std::endl;
  d += r.Fixed();               // use r

  // Saving and restoring with a copy of r
  RandomLib::Random s(r);       // copy r's state into s via copy constructor
  l += r.Integer();             // use r some more
  r = s;               // restore r's state from s via copy assignment

  // Saving and restoring with Count()
  long long c = r.Count();      // save position in r's stream
  b ^= r.Boolean();             // use r
  r.SetCount(c);                // restore r from saved count

  // Saving and restoring to file
  {
    std::ofstream f("rand.bin", std::ios::binary);
    r.Save(f);                  // save r in binary mode to rand.bin
  }
  {
    std::ifstream f("rand.bin", std::ios::binary);
    s.Load(f);                  // load saved state to s
  }
  // Saving as text
  {
    std::ofstream f("rand.txt");
    f << "Random number state:\n" << r << std::endl; // operator<<
  }
  #if HAVE_BOOST_SERIALIZATION
  // Saving and restoring the state using boost serialization
  {
    std::ofstream f("rand.xml");
    boost::archive::xml_oarchive oa(f);
    oa << BOOST_SERIALIZATION_NVP(r);   // save r to xml file rand.xml
  }
  {
    std::ifstream f("rand.xml");
    boost::archive::xml_iarchive ia(f);
    ia >> BOOST_SERIALIZATION_NVP(s);   // load saved state to s
  }
  #endif
  // Initializing with copy or modification of seed
  s.Reseed(r.Seed());           // s reseeded with r's seed
  {
    std::vector<unsigned long> v(r.Seed());
    v.push_back(1);
    s.Reseed(v);                // s reseeded with 1 appended to r's seed
  }

As you can see in this example, you can use Boost serialization to save and restore the state of a Random object to various types of archives provided you have the Boost serialization library installed (see http://www.boost.org). To turn this feature on, compile any code which includes RandomLib/Random.hpp with HAVE_BOOST_SERIALIZATION defined to be 1, and link the resulting code with libboost_serialization. In order to declare the boost archives, you will need to include the appropriate header file, e.g.,

  #include <boost/archive/xml_iarchive.hpp>
  #include <boost/archive/xml_oarchive.hpp>

With some versions of Boost, it is apparently necessary for these includes to precede the inclusion of Randomlib/Random.hpp.

Back to Other random distributions. Forward to Programming tips. Up to Contents.