/* boost random_demo.cpp profane demo * * Copyright Jens Maurer 2000 * Permission to use, copy, modify, sell, and distribute this software * is hereby granted without fee provided that the above copyright notice * appears in all copies and that both that copyright notice and this * permission notice appear in supporting documentation, * * Jens Maurer makes no representations about the suitability of this * software for any purpose. It is provided "as is" without express or * implied warranty. * * $Id: random_demo.cpp,v 1.15 2003/07/14 20:09:11 jmaurer Exp $ * * A short demo program how to use the random number library. modified to exhibit overflow by Samuel Krempp, august 2004. */ #include #include #include #include // std::time #include #include class coin_flipper { public: typedef boost::uint32_t result_type; result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; } result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 2-1; } result_type operator()() { boost::uint32_t k = (rng.max()-rng.min()) / (max()-min()+1); return (rng()-rng.min())/k; } coin_flipper() : rng() {} private: boost::mt19937 rng; }; typedef coin_flipper base_generator_type; // This is a reproducible simulation experiment. See main(). void experiment(base_generator_type & generator) { typedef boost::uniform_int distribution_type; typedef boost::variate_generator gen_type; gen_type die_gen(generator, distribution_type(0, (boost::uint32_t) (0xFFFFFFFF) )); boost::generator_iterator die(&die_gen); for(int i = 0; i < 10; i++) std::cout << " ---> " << std::setw(10) << std::setfill('0') << *die++ << "\n"; } int main() { base_generator_type generator; std::cout << "10 samples of a uniform distribution in [0..1):\n"; std::cout << "\nexperiment: roll a die 10 times:\n"; // You can save a generator's state by copy construction. base_generator_type saved_generator = generator; experiment(generator); std::cout << "redo the experiment to verify it:\n"; experiment(saved_generator); return 0; }