1 /* boost random/linear_congruential.hpp header file
3 * Copyright Jens Maurer 2000-2001
4 * Distributed under the Boost Software License, Version 1.0. (See
5 * accompanying file LICENSE_1_0.txt or copy at
6 * http://www.boost.org/LICENSE_1_0.txt)
8 * See http://www.boost.org for most recent version including documentation.
13 * 2001-02-18 moved to individual header files
16 #ifndef BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
17 #define BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
21 #include <boost/assert.hpp>
22 #include <boost/config.hpp>
23 #include <boost/cstdint.hpp>
24 #include <boost/limits.hpp>
25 #include <boost/static_assert.hpp>
26 #include <boost/type_traits/is_arithmetic.hpp>
27 #include <boost/random/detail/config.hpp>
28 #include <boost/random/detail/const_mod.hpp>
29 #include <boost/random/detail/seed.hpp>
30 #include <boost/random/detail/seed_impl.hpp>
31 #include <boost/detail/workaround.hpp>
33 #include <boost/random/detail/disable_warnings.hpp>
39 * Instantiations of class template linear_congruential_engine model a
40 * \pseudo_random_number_generator. Linear congruential pseudo-random
41 * number generators are described in:
44 * "Mathematical methods in large-scale computing units", D. H. Lehmer,
45 * Proc. 2nd Symposium on Large-Scale Digital Calculating Machines,
46 * Harvard University Press, 1951, pp. 141-146
49 * Let x(n) denote the sequence of numbers returned by some pseudo-random
50 * number generator. Then for the linear congruential generator,
51 * x(n+1) := (a * x(n) + c) mod m. Parameters for the generator are
52 * x(0), a, c, m. The template parameter IntType shall denote an integral
53 * type. It must be large enough to hold values a, c, and m. The template
54 * parameters a and c must be smaller than m.
56 * Note: The quality of the generator crucially depends on the choice of
57 * the parameters. User code should use one of the sensibly parameterized
58 * generators such as minstd_rand instead.
60 template<class IntType, IntType a, IntType c, IntType m>
61 class linear_congruential_engine
64 typedef IntType result_type;
66 // Required for old Boost.Random concept
67 BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
69 BOOST_STATIC_CONSTANT(IntType, multiplier = a);
70 BOOST_STATIC_CONSTANT(IntType, increment = c);
71 BOOST_STATIC_CONSTANT(IntType, modulus = m);
72 BOOST_STATIC_CONSTANT(IntType, default_seed = 1);
74 BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
75 BOOST_STATIC_ASSERT(m == 0 || a < m);
76 BOOST_STATIC_ASSERT(m == 0 || c < m);
79 * Constructs a @c linear_congruential_engine, using the default seed
81 linear_congruential_engine() { seed(); }
84 * Constructs a @c linear_congruential_engine, seeding it with @c x0.
86 BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(linear_congruential_engine,
91 * Constructs a @c linear_congruential_engine, seeding it with values
92 * produced by a call to @c seq.generate().
94 BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(linear_congruential_engine,
99 * Constructs a @c linear_congruential_engine and seeds it
100 * with values taken from the itrator range [first, last)
101 * and adjusts first to point to the element after the last one
102 * used. If there are not enough elements, throws @c std::invalid_argument.
104 * first and last must be input iterators.
107 linear_congruential_engine(It& first, It last)
112 // compiler-generated copy constructor and assignment operator are fine
115 * Calls seed(default_seed)
117 void seed() { seed(default_seed); }
120 * If c mod m is zero and x0 mod m is zero, changes the current value of
121 * the generator to 1. Otherwise, changes it to x0 mod m. If c is zero,
122 * distinct seeds in the range [1,m) will leave the generator in distinct
123 * states. If c is not zero, the range is [0,m).
125 BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(linear_congruential_engine, IntType, x0_)
127 // Work around a msvc 12/14 optimizer bug, which causes
128 // the line _x = 1 to run unconditionally sometimes.
129 // Creating a local copy seems to make it work.
131 // wrap _x if it doesn't fit in the destination
137 // handle negative seeds
141 // adjust to the correct range
142 if(increment == 0 && _x == 0) {
145 BOOST_ASSERT(_x >= (min)());
146 BOOST_ASSERT(_x <= (max)());
150 * Seeds a @c linear_congruential_engine using values from a SeedSeq.
152 BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(linear_congruential_engine, SeedSeq, seq)
153 { seed(detail::seed_one_int<IntType, m>(seq)); }
156 * seeds a @c linear_congruential_engine with values taken
157 * from the itrator range [first, last) and adjusts @c first to
158 * point to the element after the last one used. If there are
159 * not enough elements, throws @c std::invalid_argument.
161 * @c first and @c last must be input iterators.
164 void seed(It& first, It last)
165 { seed(detail::get_one_int<IntType, m>(first, last)); }
168 * Returns the smallest value that the @c linear_congruential_engine
171 static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
172 { return c == 0 ? 1 : 0; }
174 * Returns the largest value that the @c linear_congruential_engine
177 static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
178 { return modulus-1; }
180 /** Returns the next value of the @c linear_congruential_engine. */
183 _x = const_mod<IntType, m>::mult_add(a, _x, c);
187 /** Fills a range with random values */
189 void generate(Iter first, Iter last)
190 { detail::generate_from_int(*this, first, last); }
192 /** Advances the state of the generator by @c z. */
193 void discard(boost::uintmax_t z)
195 typedef const_mod<IntType, m> mod_type;
196 IntType b_inv = mod_type::invert(a-1);
197 IntType b_gcd = mod_type::mult(a-1, b_inv);
199 IntType a_z = mod_type::pow(a, z);
200 _x = mod_type::mult_add(a_z, _x,
201 mod_type::mult(mod_type::mult(c, b_inv), a_z - 1));
203 // compute (a^z - 1)*c % (b_gcd * m) / (b / b_gcd) * inv(b / b_gcd)
204 // we're storing the intermediate result / b_gcd
205 IntType a_zm1_over_gcd = 0;
206 IntType a_km1_over_gcd = (a - 1) / b_gcd;
207 boost::uintmax_t exponent = z;
208 while(exponent != 0) {
209 if(exponent % 2 == 1) {
213 mod_type::mult(a_zm1_over_gcd, a_km1_over_gcd),
214 mod_type::add(a_zm1_over_gcd, a_km1_over_gcd));
216 a_km1_over_gcd = mod_type::mult_add(
218 mod_type::mult(a_km1_over_gcd, a_km1_over_gcd),
219 mod_type::add(a_km1_over_gcd, a_km1_over_gcd));
223 IntType a_z = mod_type::mult_add(b_gcd, a_zm1_over_gcd, 1);
224 IntType num = mod_type::mult(c, a_zm1_over_gcd);
225 b_inv = mod_type::invert((a-1)/b_gcd);
226 _x = mod_type::mult_add(a_z, _x, mod_type::mult(b_inv, num));
230 friend bool operator==(const linear_congruential_engine& x,
231 const linear_congruential_engine& y)
232 { return x._x == y._x; }
233 friend bool operator!=(const linear_congruential_engine& x,
234 const linear_congruential_engine& y)
235 { return !(x == y); }
237 #if !defined(BOOST_RANDOM_NO_STREAM_OPERATORS)
238 /** Writes a @c linear_congruential_engine to a @c std::ostream. */
239 template<class CharT, class Traits>
240 friend std::basic_ostream<CharT,Traits>&
241 operator<<(std::basic_ostream<CharT,Traits>& os,
242 const linear_congruential_engine& lcg)
247 /** Reads a @c linear_congruential_engine from a @c std::istream. */
248 template<class CharT, class Traits>
249 friend std::basic_istream<CharT,Traits>&
250 operator>>(std::basic_istream<CharT,Traits>& is,
251 linear_congruential_engine& lcg)
260 /// \cond show_private
262 template<class CharT, class Traits>
263 void read(std::basic_istream<CharT, Traits>& is) {
266 if(x >= (min)() && x <= (max)()) {
269 is.setstate(std::ios_base::failbit);
279 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
280 // A definition is required even for integral static constants
281 template<class IntType, IntType a, IntType c, IntType m>
282 const bool linear_congruential_engine<IntType, a, c, m>::has_fixed_range;
283 template<class IntType, IntType a, IntType c, IntType m>
284 const IntType linear_congruential_engine<IntType,a,c,m>::multiplier;
285 template<class IntType, IntType a, IntType c, IntType m>
286 const IntType linear_congruential_engine<IntType,a,c,m>::increment;
287 template<class IntType, IntType a, IntType c, IntType m>
288 const IntType linear_congruential_engine<IntType,a,c,m>::modulus;
289 template<class IntType, IntType a, IntType c, IntType m>
290 const IntType linear_congruential_engine<IntType,a,c,m>::default_seed;
293 /// \cond show_deprecated
295 // provided for backwards compatibility
296 template<class IntType, IntType a, IntType c, IntType m, IntType val = 0>
297 class linear_congruential : public linear_congruential_engine<IntType, a, c, m>
299 typedef linear_congruential_engine<IntType, a, c, m> base_type;
301 linear_congruential(IntType x0 = 1) : base_type(x0) {}
303 linear_congruential(It& first, It last) : base_type(first, last) {}
309 * The specialization \minstd_rand0 was originally suggested in
312 * A pseudo-random number generator for the System/360, P.A. Lewis,
313 * A.S. Goodman, J.M. Miller, IBM Systems Journal, Vol. 8, No. 2,
317 * It is examined more closely together with \minstd_rand in
320 * "Random Number Generators: Good ones are hard to find",
321 * Stephen K. Park and Keith W. Miller, Communications of
322 * the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201
325 typedef linear_congruential_engine<uint32_t, 16807, 0, 2147483647> minstd_rand0;
327 /** The specialization \minstd_rand was suggested in
330 * "Random Number Generators: Good ones are hard to find",
331 * Stephen K. Park and Keith W. Miller, Communications of
332 * the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201
335 typedef linear_congruential_engine<uint32_t, 48271, 0, 2147483647> minstd_rand;
338 #if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
340 * Class @c rand48 models a \pseudo_random_number_generator. It uses
341 * the linear congruential algorithm with the parameters a = 0x5DEECE66D,
342 * c = 0xB, m = 2**48. It delivers identical results to the @c lrand48()
343 * function available on some systems (assuming lcong48 has not been called).
345 * It is only available on systems where @c uint64_t is provided as an
346 * integral type, so that for example static in-class constants and/or
347 * enum definitions with large @c uint64_t numbers work.
352 typedef boost::uint32_t result_type;
354 BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
356 * Returns the smallest value that the generator can produce
358 static BOOST_CONSTEXPR uint32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () { return 0; }
360 * Returns the largest value that the generator can produce
362 static BOOST_CONSTEXPR uint32_t max BOOST_PREVENT_MACRO_SUBSTITUTION ()
363 { return 0x7FFFFFFF; }
365 /** Seeds the generator with the default seed. */
366 rand48() : lcf(cnv(static_cast<uint32_t>(1))) {}
368 * Constructs a \rand48 generator with x(0) := (x0 << 16) | 0x330e.
370 BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(rand48, result_type, x0)
373 * Seeds the generator with values produced by @c seq.generate().
375 BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(rand48, SeedSeq, seq)
378 * Seeds the generator using values from an iterator range,
379 * and updates first to point one past the last value consumed.
381 template<class It> rand48(It& first, It last) : lcf(first, last) { }
383 // compiler-generated copy ctor and assignment operator are fine
385 /** Seeds the generator with the default seed. */
386 void seed() { seed(static_cast<uint32_t>(1)); }
388 * Changes the current value x(n) of the generator to (x0 << 16) | 0x330e.
390 BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(rand48, result_type, x0)
391 { lcf.seed(cnv(x0)); }
393 * Seeds the generator using values from an iterator range,
394 * and updates first to point one past the last value consumed.
396 template<class It> void seed(It& first, It last) { lcf.seed(first,last); }
398 * Seeds the generator with values produced by @c seq.generate().
400 BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(rand48, SeedSeq, seq)
403 /** Returns the next value of the generator. */
404 uint32_t operator()() { return static_cast<uint32_t>(lcf() >> 17); }
406 /** Advances the state of the generator by @c z. */
407 void discard(boost::uintmax_t z) { lcf.discard(z); }
409 /** Fills a range with random values */
411 void generate(Iter first, Iter last)
413 for(; first != last; ++first) {
418 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
419 /** Writes a @c rand48 to a @c std::ostream. */
420 template<class CharT,class Traits>
421 friend std::basic_ostream<CharT,Traits>&
422 operator<<(std::basic_ostream<CharT,Traits>& os, const rand48& r)
423 { os << r.lcf; return os; }
425 /** Reads a @c rand48 from a @c std::istream. */
426 template<class CharT,class Traits>
427 friend std::basic_istream<CharT,Traits>&
428 operator>>(std::basic_istream<CharT,Traits>& is, rand48& r)
429 { is >> r.lcf; return is; }
433 * Returns true if the two generators will produce identical
434 * sequences of values.
436 friend bool operator==(const rand48& x, const rand48& y)
437 { return x.lcf == y.lcf; }
439 * Returns true if the two generators will produce different
440 * sequences of values.
442 friend bool operator!=(const rand48& x, const rand48& y)
443 { return !(x == y); }
445 /// \cond show_private
446 typedef random::linear_congruential_engine<uint64_t,
447 // xxxxULL is not portable
448 uint64_t(0xDEECE66DUL) | (uint64_t(0x5) << 32),
449 0xB, uint64_t(1)<<48> lcf_t;
452 static boost::uint64_t cnv(boost::uint32_t x)
453 { return (static_cast<uint64_t>(x) << 16) | 0x330e; }
456 #endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */
458 } // namespace random
460 using random::minstd_rand0;
461 using random::minstd_rand;
462 using random::rand48;
466 #include <boost/random/detail/enable_warnings.hpp>
468 #endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP