Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:51:11

0001 /* boost random/linear_congruential.hpp header file
0002  *
0003  * Copyright Jens Maurer 2000-2001
0004  * Distributed under the Boost Software License, Version 1.0. (See
0005  * accompanying file LICENSE_1_0.txt or copy at
0006  * http://www.boost.org/LICENSE_1_0.txt)
0007  *
0008  * See http://www.boost.org for most recent version including documentation.
0009  *
0010  * $Id$
0011  *
0012  * Revision history
0013  *  2001-02-18  moved to individual header files
0014  */
0015 
0016 #ifndef BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
0017 #define BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
0018 
0019 #include <iostream>
0020 #include <stdexcept>
0021 #include <boost/assert.hpp>
0022 #include <boost/config.hpp>
0023 #include <boost/cstdint.hpp>
0024 #include <boost/limits.hpp>
0025 #include <boost/static_assert.hpp>
0026 #include <boost/type_traits/is_arithmetic.hpp>
0027 #include <boost/random/detail/config.hpp>
0028 #include <boost/random/detail/const_mod.hpp>
0029 #include <boost/random/detail/seed.hpp>
0030 #include <boost/random/detail/seed_impl.hpp>
0031 #include <boost/detail/workaround.hpp>
0032 
0033 #include <boost/random/detail/disable_warnings.hpp>
0034 
0035 namespace boost {
0036 namespace random {
0037 
0038 /**
0039  * Instantiations of class template linear_congruential_engine model a
0040  * \pseudo_random_number_generator. Linear congruential pseudo-random
0041  * number generators are described in:
0042  *
0043  *  @blockquote
0044  *  "Mathematical methods in large-scale computing units", D. H. Lehmer,
0045  *  Proc. 2nd Symposium on Large-Scale Digital Calculating Machines,
0046  *  Harvard University Press, 1951, pp. 141-146
0047  *  @endblockquote
0048  *
0049  * Let x(n) denote the sequence of numbers returned by some pseudo-random
0050  * number generator. Then for the linear congruential generator,
0051  * x(n+1) := (a * x(n) + c) mod m. Parameters for the generator are
0052  * x(0), a, c, m. The template parameter IntType shall denote an integral
0053  * type. It must be large enough to hold values a, c, and m. The template
0054  * parameters a and c must be smaller than m.
0055  *
0056  * Note: The quality of the generator crucially depends on the choice of
0057  * the parameters. User code should use one of the sensibly parameterized
0058  * generators such as minstd_rand instead.
0059  */
0060 template<class IntType, IntType a, IntType c, IntType m>
0061 class linear_congruential_engine
0062 {
0063 public:
0064     typedef IntType result_type;
0065 
0066     // Required for old Boost.Random concept
0067     BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
0068 
0069     BOOST_STATIC_CONSTANT(IntType, multiplier = a);
0070     BOOST_STATIC_CONSTANT(IntType, increment = c);
0071     BOOST_STATIC_CONSTANT(IntType, modulus = m);
0072     BOOST_STATIC_CONSTANT(IntType, default_seed = 1);
0073     
0074     BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
0075     BOOST_STATIC_ASSERT(m == 0 || a < m);
0076     BOOST_STATIC_ASSERT(m == 0 || c < m);
0077     
0078     /**
0079      * Constructs a @c linear_congruential_engine, using the default seed
0080      */
0081     linear_congruential_engine() { seed(); }
0082 
0083     /**
0084      * Constructs a @c linear_congruential_engine, seeding it with @c x0.
0085      */
0086     BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(linear_congruential_engine,
0087                                                IntType, x0)
0088     { seed(x0); }
0089     
0090     /**
0091      * Constructs a @c linear_congruential_engine, seeding it with values
0092      * produced by a call to @c seq.generate().
0093      */
0094     BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(linear_congruential_engine,
0095                                              SeedSeq, seq)
0096     { seed(seq); }
0097 
0098     /**
0099      * Constructs a @c linear_congruential_engine  and seeds it
0100      * with values taken from the itrator range [first, last)
0101      * and adjusts first to point to the element after the last one
0102      * used.  If there are not enough elements, throws @c std::invalid_argument.
0103      *
0104      * first and last must be input iterators.
0105      */
0106     template<class It>
0107     linear_congruential_engine(It& first, It last)
0108     {
0109         seed(first, last);
0110     }
0111 
0112     // compiler-generated copy constructor and assignment operator are fine
0113 
0114     /**
0115      * Calls seed(default_seed)
0116      */
0117     void seed() { seed(default_seed); }
0118 
0119     /**
0120      * If c mod m is zero and x0 mod m is zero, changes the current value of
0121      * the generator to 1. Otherwise, changes it to x0 mod m. If c is zero,
0122      * distinct seeds in the range [1,m) will leave the generator in distinct
0123      * states. If c is not zero, the range is [0,m).
0124      */
0125     BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(linear_congruential_engine, IntType, x0_)
0126     {
0127         // Work around a msvc 12/14 optimizer bug, which causes
0128         // the line _x = 1 to run unconditionally sometimes.
0129         // Creating a local copy seems to make it work.
0130         IntType x0 = x0_;
0131         // wrap _x if it doesn't fit in the destination
0132         if(modulus == 0) {
0133             _x = x0;
0134         } else {
0135             _x = x0 % modulus;
0136         }
0137         // handle negative seeds
0138         if(_x < 0) {
0139             _x += modulus;
0140         }
0141         // adjust to the correct range
0142         if(increment == 0 && _x == 0) {
0143             _x = 1;
0144         }
0145         BOOST_ASSERT(_x >= (min)());
0146         BOOST_ASSERT(_x <= (max)());
0147     }
0148 
0149     /**
0150      * Seeds a @c linear_congruential_engine using values from a SeedSeq.
0151      */
0152     BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(linear_congruential_engine, SeedSeq, seq)
0153     { seed(detail::seed_one_int<IntType, m>(seq)); }
0154 
0155     /**
0156      * seeds a @c linear_congruential_engine with values taken
0157      * from the itrator range [first, last) and adjusts @c first to
0158      * point to the element after the last one used.  If there are
0159      * not enough elements, throws @c std::invalid_argument.
0160      *
0161      * @c first and @c last must be input iterators.
0162      */
0163     template<class It>
0164     void seed(It& first, It last)
0165     { seed(detail::get_one_int<IntType, m>(first, last)); }
0166 
0167     /**
0168      * Returns the smallest value that the @c linear_congruential_engine
0169      * can produce.
0170      */
0171     static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
0172     { return c == 0 ? 1 : 0; }
0173     /**
0174      * Returns the largest value that the @c linear_congruential_engine
0175      * can produce.
0176      */
0177     static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
0178     { return modulus-1; }
0179 
0180     /** Returns the next value of the @c linear_congruential_engine. */
0181     IntType operator()()
0182     {
0183         _x = const_mod<IntType, m>::mult_add(a, _x, c);
0184         return _x;
0185     }
0186   
0187     /** Fills a range with random values */
0188     template<class Iter>
0189     void generate(Iter first, Iter last)
0190     { detail::generate_from_int(*this, first, last); }
0191 
0192     /** Advances the state of the generator by @c z. */
0193     void discard(boost::uintmax_t z)
0194     {
0195         typedef const_mod<IntType, m> mod_type;
0196         IntType b_inv = mod_type::invert(a-1);
0197         IntType b_gcd = mod_type::mult(a-1, b_inv);
0198         if(b_gcd == 1) {
0199             IntType a_z = mod_type::pow(a, z);
0200             _x = mod_type::mult_add(a_z, _x, 
0201                 mod_type::mult(mod_type::mult(c, b_inv), a_z - 1));
0202         } else {
0203             // compute (a^z - 1)*c % (b_gcd * m) / (b / b_gcd) * inv(b / b_gcd)
0204             // we're storing the intermediate result / b_gcd
0205             IntType a_zm1_over_gcd = 0;
0206             IntType a_km1_over_gcd = (a - 1) / b_gcd;
0207             boost::uintmax_t exponent = z;
0208             while(exponent != 0) {
0209                 if(exponent % 2 == 1) {
0210                     a_zm1_over_gcd =
0211                         mod_type::mult_add(
0212                             b_gcd,
0213                             mod_type::mult(a_zm1_over_gcd, a_km1_over_gcd),
0214                             mod_type::add(a_zm1_over_gcd, a_km1_over_gcd));
0215                 }
0216                 a_km1_over_gcd = mod_type::mult_add(
0217                     b_gcd,
0218                     mod_type::mult(a_km1_over_gcd, a_km1_over_gcd),
0219                     mod_type::add(a_km1_over_gcd, a_km1_over_gcd));
0220                 exponent /= 2;
0221             }
0222             
0223             IntType a_z = mod_type::mult_add(b_gcd, a_zm1_over_gcd, 1);
0224             IntType num = mod_type::mult(c, a_zm1_over_gcd);
0225             b_inv = mod_type::invert((a-1)/b_gcd);
0226             _x = mod_type::mult_add(a_z, _x, mod_type::mult(b_inv, num));
0227         }
0228     }
0229 
0230     friend bool operator==(const linear_congruential_engine& x,
0231                            const linear_congruential_engine& y)
0232     { return x._x == y._x; }
0233     friend bool operator!=(const linear_congruential_engine& x,
0234                            const linear_congruential_engine& y)
0235     { return !(x == y); }
0236     
0237 #if !defined(BOOST_RANDOM_NO_STREAM_OPERATORS)
0238     /** Writes a @c linear_congruential_engine to a @c std::ostream. */
0239     template<class CharT, class Traits>
0240     friend std::basic_ostream<CharT,Traits>&
0241     operator<<(std::basic_ostream<CharT,Traits>& os,
0242                const linear_congruential_engine& lcg)
0243     {
0244         return os << lcg._x;
0245     }
0246 
0247     /** Reads a @c linear_congruential_engine from a @c std::istream. */
0248     template<class CharT, class Traits>
0249     friend std::basic_istream<CharT,Traits>&
0250     operator>>(std::basic_istream<CharT,Traits>& is,
0251                linear_congruential_engine& lcg)
0252     {
0253         lcg.read(is);
0254         return is;
0255     }
0256 #endif
0257 
0258 private:
0259 
0260     /// \cond show_private
0261 
0262     template<class CharT, class Traits>
0263     void read(std::basic_istream<CharT, Traits>& is) {
0264         IntType x;
0265         if(is >> x) {
0266             if(x >= (min)() && x <= (max)()) {
0267                 _x = x;
0268             } else {
0269                 is.setstate(std::ios_base::failbit);
0270             }
0271         }
0272     }
0273 
0274     /// \endcond
0275 
0276     IntType _x;
0277 };
0278 
0279 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
0280 //  A definition is required even for integral static constants
0281 template<class IntType, IntType a, IntType c, IntType m>
0282 const bool linear_congruential_engine<IntType, a, c, m>::has_fixed_range;
0283 template<class IntType, IntType a, IntType c, IntType m>
0284 const IntType linear_congruential_engine<IntType,a,c,m>::multiplier;
0285 template<class IntType, IntType a, IntType c, IntType m>
0286 const IntType linear_congruential_engine<IntType,a,c,m>::increment;
0287 template<class IntType, IntType a, IntType c, IntType m>
0288 const IntType linear_congruential_engine<IntType,a,c,m>::modulus;
0289 template<class IntType, IntType a, IntType c, IntType m>
0290 const IntType linear_congruential_engine<IntType,a,c,m>::default_seed;
0291 #endif
0292 
0293 /// \cond show_deprecated
0294 
0295 // provided for backwards compatibility
0296 template<class IntType, IntType a, IntType c, IntType m, IntType val = 0>
0297 class linear_congruential : public linear_congruential_engine<IntType, a, c, m>
0298 {
0299     typedef linear_congruential_engine<IntType, a, c, m> base_type;
0300 public:
0301     linear_congruential(IntType x0 = 1) : base_type(x0) {}
0302     template<class It>
0303     linear_congruential(It& first, It last) : base_type(first, last) {}
0304 };
0305 
0306 /// \endcond
0307 
0308 /**
0309  * The specialization \minstd_rand0 was originally suggested in
0310  *
0311  *  @blockquote
0312  *  A pseudo-random number generator for the System/360, P.A. Lewis,
0313  *  A.S. Goodman, J.M. Miller, IBM Systems Journal, Vol. 8, No. 2,
0314  *  1969, pp. 136-146
0315  *  @endblockquote
0316  *
0317  * It is examined more closely together with \minstd_rand in
0318  *
0319  *  @blockquote
0320  *  "Random Number Generators: Good ones are hard to find",
0321  *  Stephen K. Park and Keith W. Miller, Communications of
0322  *  the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201 
0323  *  @endblockquote
0324  */
0325 typedef linear_congruential_engine<uint32_t, 16807, 0, 2147483647> minstd_rand0;
0326 
0327 /** The specialization \minstd_rand was suggested in
0328  *
0329  *  @blockquote
0330  *  "Random Number Generators: Good ones are hard to find",
0331  *  Stephen K. Park and Keith W. Miller, Communications of
0332  *  the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201
0333  *  @endblockquote
0334  */
0335 typedef linear_congruential_engine<uint32_t, 48271, 0, 2147483647> minstd_rand;
0336 
0337 
0338 #if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
0339 /**
0340  * Class @c rand48 models a \pseudo_random_number_generator. It uses
0341  * the linear congruential algorithm with the parameters a = 0x5DEECE66D,
0342  * c = 0xB, m = 2**48. It delivers identical results to the @c lrand48()
0343  * function available on some systems (assuming lcong48 has not been called).
0344  *
0345  * It is only available on systems where @c uint64_t is provided as an
0346  * integral type, so that for example static in-class constants and/or
0347  * enum definitions with large @c uint64_t numbers work.
0348  */
0349 class rand48 
0350 {
0351 public:
0352     typedef boost::uint32_t result_type;
0353 
0354     BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
0355     /**
0356      * Returns the smallest value that the generator can produce
0357      */
0358     static BOOST_CONSTEXPR uint32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () { return 0; }
0359     /**
0360      * Returns the largest value that the generator can produce
0361      */
0362     static BOOST_CONSTEXPR uint32_t max BOOST_PREVENT_MACRO_SUBSTITUTION ()
0363     { return 0x7FFFFFFF; }
0364   
0365     /** Seeds the generator with the default seed. */
0366     rand48() : lcf(cnv(static_cast<uint32_t>(1))) {}
0367     /**
0368      * Constructs a \rand48 generator with x(0) := (x0 << 16) | 0x330e.
0369      */
0370     BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(rand48, result_type, x0)
0371     { seed(x0); }
0372     /**
0373      * Seeds the generator with values produced by @c seq.generate().
0374      */
0375     BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(rand48, SeedSeq, seq)
0376     { seed(seq); }
0377     /**
0378      * Seeds the generator using values from an iterator range,
0379      * and updates first to point one past the last value consumed.
0380      */
0381     template<class It> rand48(It& first, It last) : lcf(first, last) { }
0382 
0383     // compiler-generated copy ctor and assignment operator are fine
0384 
0385     /** Seeds the generator with the default seed. */
0386     void seed() { seed(static_cast<uint32_t>(1)); }
0387     /**
0388      * Changes the current value x(n) of the generator to (x0 << 16) | 0x330e.
0389      */
0390     BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(rand48, result_type, x0)
0391     { lcf.seed(cnv(x0)); }
0392     /**
0393      * Seeds the generator using values from an iterator range,
0394      * and updates first to point one past the last value consumed.
0395      */
0396     template<class It> void seed(It& first, It last) { lcf.seed(first,last); }
0397     /**
0398      * Seeds the generator with values produced by @c seq.generate().
0399      */
0400     BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(rand48, SeedSeq, seq)
0401     { lcf.seed(seq); }
0402 
0403     /**  Returns the next value of the generator. */
0404     uint32_t operator()() { return static_cast<uint32_t>(lcf() >> 17); }
0405     
0406     /** Advances the state of the generator by @c z. */
0407     void discard(boost::uintmax_t z) { lcf.discard(z); }
0408   
0409     /** Fills a range with random values */
0410     template<class Iter>
0411     void generate(Iter first, Iter last)
0412     {
0413         for(; first != last; ++first) {
0414             *first = (*this)();
0415         }
0416     }
0417 
0418 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
0419     /**  Writes a @c rand48 to a @c std::ostream. */
0420     template<class CharT,class Traits>
0421     friend std::basic_ostream<CharT,Traits>&
0422     operator<<(std::basic_ostream<CharT,Traits>& os, const rand48& r)
0423     { os << r.lcf; return os; }
0424 
0425     /** Reads a @c rand48 from a @c std::istream. */
0426     template<class CharT,class Traits>
0427     friend std::basic_istream<CharT,Traits>&
0428     operator>>(std::basic_istream<CharT,Traits>& is, rand48& r)
0429     { is >> r.lcf; return is; }
0430 #endif
0431 
0432     /**
0433      * Returns true if the two generators will produce identical
0434      * sequences of values.
0435      */
0436     friend bool operator==(const rand48& x, const rand48& y)
0437     { return x.lcf == y.lcf; }
0438     /**
0439      * Returns true if the two generators will produce different
0440      * sequences of values.
0441      */
0442     friend bool operator!=(const rand48& x, const rand48& y)
0443     { return !(x == y); }
0444 private:
0445     /// \cond show_private
0446     typedef random::linear_congruential_engine<uint64_t,
0447         // xxxxULL is not portable
0448         uint64_t(0xDEECE66DUL) | (uint64_t(0x5) << 32),
0449         0xB, uint64_t(1)<<48> lcf_t;
0450     lcf_t lcf;
0451 
0452     static boost::uint64_t cnv(boost::uint32_t x)
0453     { return (static_cast<uint64_t>(x) << 16) | 0x330e; }
0454     /// \endcond
0455 };
0456 #endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */
0457 
0458 } // namespace random
0459 
0460 using random::minstd_rand0;
0461 using random::minstd_rand;
0462 using random::rand48;
0463 
0464 } // namespace boost
0465 
0466 #include <boost/random/detail/enable_warnings.hpp>
0467 
0468 #endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP