1/* boost random/linear_congruential.hpp header file
2 *
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)
7 *
8 * See http://www.boost.org for most recent version including documentation.
9 *
10 * $Id$
11 *
12 * Revision history
13 * 2001-02-18 moved to individual header files
14 */
15
16#ifndef BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
17#define BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
18
19#include <iostream>
20#include <stdexcept>
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>
32
33#include <boost/random/detail/disable_warnings.hpp>
34
35namespace boost {
36namespace random {
37
38/**
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:
42 *
43 * @blockquote
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
47 * @endblockquote
48 *
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.
55 *
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.
59 */
60template<class IntType, IntType a, IntType c, IntType m>
61class linear_congruential_engine
62{
63public:
64 typedef IntType result_type;
65
66 // Required for old Boost.Random concept
67 BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
68
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);
73
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);
77
78 /**
79 * Constructs a @c linear_congruential_engine, using the default seed
80 */
81 linear_congruential_engine() { seed(); }
82
83 /**
84 * Constructs a @c linear_congruential_engine, seeding it with @c x0.
85 */
86 BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(linear_congruential_engine,
87 IntType, x0)
88 { seed(x0); }
89
90 /**
91 * Constructs a @c linear_congruential_engine, seeding it with values
92 * produced by a call to @c seq.generate().
93 */
94 BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(linear_congruential_engine,
95 SeedSeq, seq)
96 { seed(seq); }
97
98 /**
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.
103 *
104 * first and last must be input iterators.
105 */
106 template<class It>
107 linear_congruential_engine(It& first, It last)
108 {
109 seed(first, last);
110 }
111
112 // compiler-generated copy constructor and assignment operator are fine
113
114 /**
115 * Calls seed(default_seed)
116 */
117 void seed() { seed(default_seed); }
118
119 /**
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).
124 */
125 BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(linear_congruential_engine, IntType, x0_)
126 {
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.
130 IntType x0 = x0_;
131 // wrap _x if it doesn't fit in the destination
132 if(modulus == 0) {
133 _x = x0;
134 } else {
135 _x = x0 % modulus;
136 }
137 // handle negative seeds
138 if(_x < 0) {
139 _x += modulus;
140 }
141 // adjust to the correct range
142 if(increment == 0 && _x == 0) {
143 _x = 1;
144 }
145 BOOST_ASSERT(_x >= (min)());
146 BOOST_ASSERT(_x <= (max)());
147 }
148
149 /**
150 * Seeds a @c linear_congruential_engine using values from a SeedSeq.
151 */
152 BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(linear_congruential_engine, SeedSeq, seq)
153 { seed(detail::seed_one_int<IntType, m>(seq)); }
154
155 /**
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.
160 *
161 * @c first and @c last must be input iterators.
162 */
163 template<class It>
164 void seed(It& first, It last)
165 { seed(detail::get_one_int<IntType, m>(first, last)); }
166
167 /**
168 * Returns the smallest value that the @c linear_congruential_engine
169 * can produce.
170 */
171 static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
172 { return c == 0 ? 1 : 0; }
173 /**
174 * Returns the largest value that the @c linear_congruential_engine
175 * can produce.
176 */
177 static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
178 { return modulus-1; }
179
180 /** Returns the next value of the @c linear_congruential_engine. */
181 IntType operator()()
182 {
183 _x = const_mod<IntType, m>::mult_add(a, _x, c);
184 return _x;
185 }
186
187 /** Fills a range with random values */
188 template<class Iter>
189 void generate(Iter first, Iter last)
190 { detail::generate_from_int(*this, first, last); }
191
192 /** Advances the state of the generator by @c z. */
193 void discard(boost::uintmax_t z)
194 {
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);
198 if(b_gcd == 1) {
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));
202 } else {
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) {
210 a_zm1_over_gcd =
211 mod_type::mult_add(
212 b_gcd,
213 mod_type::mult(a_zm1_over_gcd, a_km1_over_gcd),
214 mod_type::add(a_zm1_over_gcd, a_km1_over_gcd));
215 }
216 a_km1_over_gcd = mod_type::mult_add(
217 b_gcd,
218 mod_type::mult(a_km1_over_gcd, a_km1_over_gcd),
219 mod_type::add(a_km1_over_gcd, a_km1_over_gcd));
220 exponent /= 2;
221 }
222
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));
227 }
228 }
229
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); }
236
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)
243 {
244 return os << lcg._x;
245 }
246
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)
252 {
253 lcg.read(is);
254 return is;
255 }
256#endif
257
258private:
259
260 /// \cond show_private
261
262 template<class CharT, class Traits>
263 void read(std::basic_istream<CharT, Traits>& is) {
264 IntType x;
265 if(is >> x) {
266 if(x >= (min)() && x <= (max)()) {
267 _x = x;
268 } else {
269 is.setstate(std::ios_base::failbit);
270 }
271 }
272 }
273
274 /// \endcond
275
276 IntType _x;
277};
278
279#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
280// A definition is required even for integral static constants
281template<class IntType, IntType a, IntType c, IntType m>
282const bool linear_congruential_engine<IntType, a, c, m>::has_fixed_range;
283template<class IntType, IntType a, IntType c, IntType m>
284const IntType linear_congruential_engine<IntType,a,c,m>::multiplier;
285template<class IntType, IntType a, IntType c, IntType m>
286const IntType linear_congruential_engine<IntType,a,c,m>::increment;
287template<class IntType, IntType a, IntType c, IntType m>
288const IntType linear_congruential_engine<IntType,a,c,m>::modulus;
289template<class IntType, IntType a, IntType c, IntType m>
290const IntType linear_congruential_engine<IntType,a,c,m>::default_seed;
291#endif
292
293/// \cond show_deprecated
294
295// provided for backwards compatibility
296template<class IntType, IntType a, IntType c, IntType m, IntType val = 0>
297class linear_congruential : public linear_congruential_engine<IntType, a, c, m>
298{
299 typedef linear_congruential_engine<IntType, a, c, m> base_type;
300public:
301 linear_congruential(IntType x0 = 1) : base_type(x0) {}
302 template<class It>
303 linear_congruential(It& first, It last) : base_type(first, last) {}
304};
305
306/// \endcond
307
308/**
309 * The specialization \minstd_rand0 was originally suggested in
310 *
311 * @blockquote
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,
314 * 1969, pp. 136-146
315 * @endblockquote
316 *
317 * It is examined more closely together with \minstd_rand in
318 *
319 * @blockquote
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
323 * @endblockquote
324 */
325typedef linear_congruential_engine<uint32_t, 16807, 0, 2147483647> minstd_rand0;
326
327/** The specialization \minstd_rand was suggested in
328 *
329 * @blockquote
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
333 * @endblockquote
334 */
335typedef linear_congruential_engine<uint32_t, 48271, 0, 2147483647> minstd_rand;
336
337
338#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
339/**
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).
344 *
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.
348 */
349class rand48
350{
351public:
352 typedef boost::uint32_t result_type;
353
354 BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
355 /**
356 * Returns the smallest value that the generator can produce
357 */
358 static BOOST_CONSTEXPR uint32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () { return 0; }
359 /**
360 * Returns the largest value that the generator can produce
361 */
362 static BOOST_CONSTEXPR uint32_t max BOOST_PREVENT_MACRO_SUBSTITUTION ()
363 { return 0x7FFFFFFF; }
364
365 /** Seeds the generator with the default seed. */
366 rand48() : lcf(cnv(x: static_cast<uint32_t>(1))) {}
367 /**
368 * Constructs a \rand48 generator with x(0) := (x0 << 16) | 0x330e.
369 */
370 BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(rand48, result_type, x0)
371 { seed(x0); }
372 /**
373 * Seeds the generator with values produced by @c seq.generate().
374 */
375 BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(rand48, SeedSeq, seq)
376 { seed(seq); }
377 /**
378 * Seeds the generator using values from an iterator range,
379 * and updates first to point one past the last value consumed.
380 */
381 template<class It> rand48(It& first, It last) : lcf(first, last) { }
382
383 // compiler-generated copy ctor and assignment operator are fine
384
385 /** Seeds the generator with the default seed. */
386 void seed() { seed(x0: static_cast<uint32_t>(1)); }
387 /**
388 * Changes the current value x(n) of the generator to (x0 << 16) | 0x330e.
389 */
390 BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(rand48, result_type, x0)
391 { lcf.seed(x0_: cnv(x: x0)); }
392 /**
393 * Seeds the generator using values from an iterator range,
394 * and updates first to point one past the last value consumed.
395 */
396 template<class It> void seed(It& first, It last) { lcf.seed(first,last); }
397 /**
398 * Seeds the generator with values produced by @c seq.generate().
399 */
400 BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(rand48, SeedSeq, seq)
401 { lcf.seed(seq); }
402
403 /** Returns the next value of the generator. */
404 uint32_t operator()() { return static_cast<uint32_t>(lcf() >> 17); }
405
406 /** Advances the state of the generator by @c z. */
407 void discard(boost::uintmax_t z) { lcf.discard(z); }
408
409 /** Fills a range with random values */
410 template<class Iter>
411 void generate(Iter first, Iter last)
412 {
413 for(; first != last; ++first) {
414 *first = (*this)();
415 }
416 }
417
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; }
424
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; }
430#endif
431
432 /**
433 * Returns true if the two generators will produce identical
434 * sequences of values.
435 */
436 friend bool operator==(const rand48& x, const rand48& y)
437 { return x.lcf == y.lcf; }
438 /**
439 * Returns true if the two generators will produce different
440 * sequences of values.
441 */
442 friend bool operator!=(const rand48& x, const rand48& y)
443 { return !(x == y); }
444private:
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;
450 lcf_t lcf;
451
452 static boost::uint64_t cnv(boost::uint32_t x)
453 { return (static_cast<uint64_t>(x) << 16) | 0x330e; }
454 /// \endcond
455};
456#endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */
457
458} // namespace random
459
460using random::minstd_rand0;
461using random::minstd_rand;
462using random::rand48;
463
464} // namespace boost
465
466#include <boost/random/detail/enable_warnings.hpp>
467
468#endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
469

source code of boost/libs/random/include/boost/random/linear_congruential.hpp