linear_congruential.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. #ifndef BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
  16. #define BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
  17. #include <iostream>
  18. #include <stdexcept>
  19. #include <boost/assert.hpp>
  20. #include <boost/config.hpp>
  21. #include <boost/cstdint.hpp>
  22. #include <boost/limits.hpp>
  23. #include <boost/static_assert.hpp>
  24. #include <boost/integer/static_log2.hpp>
  25. #include <boost/mpl/if.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. #include <boost/random/detail/disable_warnings.hpp>
  33. namespace boost {
  34. namespace random {
  35. /**
  36. * Instantiations of class template linear_congruential_engine model a
  37. * \pseudo_random_number_generator. Linear congruential pseudo-random
  38. * number generators are described in:
  39. *
  40. * @blockquote
  41. * "Mathematical methods in large-scale computing units", D. H. Lehmer,
  42. * Proc. 2nd Symposium on Large-Scale Digital Calculating Machines,
  43. * Harvard University Press, 1951, pp. 141-146
  44. * @endblockquote
  45. *
  46. * Let x(n) denote the sequence of numbers returned by some pseudo-random
  47. * number generator. Then for the linear congruential generator,
  48. * x(n+1) := (a * x(n) + c) mod m. Parameters for the generator are
  49. * x(0), a, c, m. The template parameter IntType shall denote an integral
  50. * type. It must be large enough to hold values a, c, and m. The template
  51. * parameters a and c must be smaller than m.
  52. *
  53. * Note: The quality of the generator crucially depends on the choice of
  54. * the parameters. User code should use one of the sensibly parameterized
  55. * generators such as minstd_rand instead.
  56. */
  57. template<class IntType, IntType a, IntType c, IntType m>
  58. class linear_congruential_engine
  59. {
  60. public:
  61. typedef IntType result_type;
  62. // Required for old Boost.Random concept
  63. BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
  64. BOOST_STATIC_CONSTANT(IntType, multiplier = a);
  65. BOOST_STATIC_CONSTANT(IntType, increment = c);
  66. BOOST_STATIC_CONSTANT(IntType, modulus = m);
  67. BOOST_STATIC_CONSTANT(IntType, default_seed = 1);
  68. BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
  69. BOOST_STATIC_ASSERT(m == 0 || a < m);
  70. BOOST_STATIC_ASSERT(m == 0 || c < m);
  71. /**
  72. * Constructs a @c linear_congruential_engine, using the default seed
  73. */
  74. linear_congruential_engine() { seed(); }
  75. /**
  76. * Constructs a @c linear_congruential_engine, seeding it with @c x0.
  77. */
  78. BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(linear_congruential_engine,
  79. IntType, x0)
  80. { seed(x0); }
  81. /**
  82. * Constructs a @c linear_congruential_engine, seeding it with values
  83. * produced by a call to @c seq.generate().
  84. */
  85. BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(linear_congruential_engine,
  86. SeedSeq, seq)
  87. { seed(seq); }
  88. /**
  89. * Constructs a @c linear_congruential_engine and seeds it
  90. * with values taken from the itrator range [first, last)
  91. * and adjusts first to point to the element after the last one
  92. * used. If there are not enough elements, throws @c std::invalid_argument.
  93. *
  94. * first and last must be input iterators.
  95. */
  96. template<class It>
  97. linear_congruential_engine(It& first, It last)
  98. {
  99. seed(first, last);
  100. }
  101. // compiler-generated copy constructor and assignment operator are fine
  102. /**
  103. * Calls seed(default_seed)
  104. */
  105. void seed() { seed(default_seed); }
  106. /**
  107. * If c mod m is zero and x0 mod m is zero, changes the current value of
  108. * the generator to 1. Otherwise, changes it to x0 mod m. If c is zero,
  109. * distinct seeds in the range [1,m) will leave the generator in distinct
  110. * states. If c is not zero, the range is [0,m).
  111. */
  112. BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(linear_congruential_engine, IntType, x0_)
  113. {
  114. // Work around a msvc 12/14 optimizer bug, which causes
  115. // the line _x = 1 to run unconditionally sometimes.
  116. // Creating a local copy seems to make it work.
  117. IntType x0 = x0_;
  118. // wrap _x if it doesn't fit in the destination
  119. if(modulus == 0) {
  120. _x = x0;
  121. } else {
  122. _x = x0 % modulus;
  123. }
  124. // handle negative seeds
  125. if(_x <= 0 && _x != 0) {
  126. _x += modulus;
  127. }
  128. // adjust to the correct range
  129. if(increment == 0 && _x == 0) {
  130. _x = 1;
  131. }
  132. BOOST_ASSERT(_x >= (min)());
  133. BOOST_ASSERT(_x <= (max)());
  134. }
  135. /**
  136. * Seeds a @c linear_congruential_engine using values from a SeedSeq.
  137. */
  138. BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(linear_congruential_engine, SeedSeq, seq)
  139. { seed(detail::seed_one_int<IntType, m>(seq)); }
  140. /**
  141. * seeds a @c linear_congruential_engine with values taken
  142. * from the itrator range [first, last) and adjusts @c first to
  143. * point to the element after the last one used. If there are
  144. * not enough elements, throws @c std::invalid_argument.
  145. *
  146. * @c first and @c last must be input iterators.
  147. */
  148. template<class It>
  149. void seed(It& first, It last)
  150. { seed(detail::get_one_int<IntType, m>(first, last)); }
  151. /**
  152. * Returns the smallest value that the @c linear_congruential_engine
  153. * can produce.
  154. */
  155. static result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
  156. { return c == 0 ? 1 : 0; }
  157. /**
  158. * Returns the largest value that the @c linear_congruential_engine
  159. * can produce.
  160. */
  161. static result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
  162. { return modulus-1; }
  163. /** Returns the next value of the @c linear_congruential_engine. */
  164. IntType operator()()
  165. {
  166. _x = const_mod<IntType, m>::mult_add(a, _x, c);
  167. return _x;
  168. }
  169. /** Fills a range with random values */
  170. template<class Iter>
  171. void generate(Iter first, Iter last)
  172. { detail::generate_from_int(*this, first, last); }
  173. /** Advances the state of the generator by @c z. */
  174. void discard(boost::uintmax_t z)
  175. {
  176. typedef const_mod<IntType, m> mod_type;
  177. IntType b_inv = mod_type::invert(a-1);
  178. IntType b_gcd = mod_type::mult(a-1, b_inv);
  179. if(b_gcd == 1) {
  180. IntType a_z = mod_type::pow(a, z);
  181. _x = mod_type::mult_add(a_z, _x,
  182. mod_type::mult(mod_type::mult(c, b_inv), a_z - 1));
  183. } else {
  184. // compute (a^z - 1)*c % (b_gcd * m) / (b / b_gcd) * inv(b / b_gcd)
  185. // we're storing the intermediate result / b_gcd
  186. IntType a_zm1_over_gcd = 0;
  187. IntType a_km1_over_gcd = (a - 1) / b_gcd;
  188. boost::uintmax_t exponent = z;
  189. while(exponent != 0) {
  190. if(exponent % 2 == 1) {
  191. a_zm1_over_gcd =
  192. mod_type::mult_add(
  193. b_gcd,
  194. mod_type::mult(a_zm1_over_gcd, a_km1_over_gcd),
  195. mod_type::add(a_zm1_over_gcd, a_km1_over_gcd));
  196. }
  197. a_km1_over_gcd = mod_type::mult_add(
  198. b_gcd,
  199. mod_type::mult(a_km1_over_gcd, a_km1_over_gcd),
  200. mod_type::add(a_km1_over_gcd, a_km1_over_gcd));
  201. exponent /= 2;
  202. }
  203. IntType a_z = mod_type::mult_add(b_gcd, a_zm1_over_gcd, 1);
  204. IntType num = mod_type::mult(c, a_zm1_over_gcd);
  205. b_inv = mod_type::invert((a-1)/b_gcd);
  206. _x = mod_type::mult_add(a_z, _x, mod_type::mult(b_inv, num));
  207. }
  208. }
  209. friend bool operator==(const linear_congruential_engine& x,
  210. const linear_congruential_engine& y)
  211. { return x._x == y._x; }
  212. friend bool operator!=(const linear_congruential_engine& x,
  213. const linear_congruential_engine& y)
  214. { return !(x == y); }
  215. #if !defined(BOOST_RANDOM_NO_STREAM_OPERATORS)
  216. /** Writes a @c linear_congruential_engine to a @c std::ostream. */
  217. template<class CharT, class Traits>
  218. friend std::basic_ostream<CharT,Traits>&
  219. operator<<(std::basic_ostream<CharT,Traits>& os,
  220. const linear_congruential_engine& lcg)
  221. {
  222. return os << lcg._x;
  223. }
  224. /** Reads a @c linear_congruential_engine from a @c std::istream. */
  225. template<class CharT, class Traits>
  226. friend std::basic_istream<CharT,Traits>&
  227. operator>>(std::basic_istream<CharT,Traits>& is,
  228. linear_congruential_engine& lcg)
  229. {
  230. lcg.read(is);
  231. return is;
  232. }
  233. #endif
  234. private:
  235. /// \cond show_private
  236. template<class CharT, class Traits>
  237. void read(std::basic_istream<CharT, Traits>& is) {
  238. IntType x;
  239. if(is >> x) {
  240. if(x >= (min)() && x <= (max)()) {
  241. _x = x;
  242. } else {
  243. is.setstate(std::ios_base::failbit);
  244. }
  245. }
  246. }
  247. /// \endcond
  248. IntType _x;
  249. };
  250. #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
  251. // A definition is required even for integral static constants
  252. template<class IntType, IntType a, IntType c, IntType m>
  253. const bool linear_congruential_engine<IntType, a, c, m>::has_fixed_range;
  254. template<class IntType, IntType a, IntType c, IntType m>
  255. const IntType linear_congruential_engine<IntType,a,c,m>::multiplier;
  256. template<class IntType, IntType a, IntType c, IntType m>
  257. const IntType linear_congruential_engine<IntType,a,c,m>::increment;
  258. template<class IntType, IntType a, IntType c, IntType m>
  259. const IntType linear_congruential_engine<IntType,a,c,m>::modulus;
  260. template<class IntType, IntType a, IntType c, IntType m>
  261. const IntType linear_congruential_engine<IntType,a,c,m>::default_seed;
  262. #endif
  263. /// \cond show_deprecated
  264. // provided for backwards compatibility
  265. template<class IntType, IntType a, IntType c, IntType m, IntType val = 0>
  266. class linear_congruential : public linear_congruential_engine<IntType, a, c, m>
  267. {
  268. typedef linear_congruential_engine<IntType, a, c, m> base_type;
  269. public:
  270. linear_congruential(IntType x0 = 1) : base_type(x0) {}
  271. template<class It>
  272. linear_congruential(It& first, It last) : base_type(first, last) {}
  273. };
  274. /// \endcond
  275. /**
  276. * The specialization \minstd_rand0 was originally suggested in
  277. *
  278. * @blockquote
  279. * A pseudo-random number generator for the System/360, P.A. Lewis,
  280. * A.S. Goodman, J.M. Miller, IBM Systems Journal, Vol. 8, No. 2,
  281. * 1969, pp. 136-146
  282. * @endblockquote
  283. *
  284. * It is examined more closely together with \minstd_rand in
  285. *
  286. * @blockquote
  287. * "Random Number Generators: Good ones are hard to find",
  288. * Stephen K. Park and Keith W. Miller, Communications of
  289. * the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201
  290. * @endblockquote
  291. */
  292. typedef linear_congruential_engine<uint32_t, 16807, 0, 2147483647> minstd_rand0;
  293. /** The specialization \minstd_rand was suggested in
  294. *
  295. * @blockquote
  296. * "Random Number Generators: Good ones are hard to find",
  297. * Stephen K. Park and Keith W. Miller, Communications of
  298. * the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201
  299. * @endblockquote
  300. */
  301. typedef linear_congruential_engine<uint32_t, 48271, 0, 2147483647> minstd_rand;
  302. #if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
  303. /**
  304. * Class @c rand48 models a \pseudo_random_number_generator. It uses
  305. * the linear congruential algorithm with the parameters a = 0x5DEECE66D,
  306. * c = 0xB, m = 2**48. It delivers identical results to the @c lrand48()
  307. * function available on some systems (assuming lcong48 has not been called).
  308. *
  309. * It is only available on systems where @c uint64_t is provided as an
  310. * integral type, so that for example static in-class constants and/or
  311. * enum definitions with large @c uint64_t numbers work.
  312. */
  313. class rand48
  314. {
  315. public:
  316. typedef boost::uint32_t result_type;
  317. BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
  318. /**
  319. * Returns the smallest value that the generator can produce
  320. */
  321. static uint32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () { return 0; }
  322. /**
  323. * Returns the largest value that the generator can produce
  324. */
  325. static uint32_t max BOOST_PREVENT_MACRO_SUBSTITUTION ()
  326. { return 0x7FFFFFFF; }
  327. /** Seeds the generator with the default seed. */
  328. rand48() : lcf(cnv(static_cast<uint32_t>(1))) {}
  329. /**
  330. * Constructs a \rand48 generator with x(0) := (x0 << 16) | 0x330e.
  331. */
  332. BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(rand48, result_type, x0)
  333. { seed(x0); }
  334. /**
  335. * Seeds the generator with values produced by @c seq.generate().
  336. */
  337. BOOST_RANDOM_DETAIL_SEED_SEQ_CONSTRUCTOR(rand48, SeedSeq, seq)
  338. { seed(seq); }
  339. /**
  340. * Seeds the generator using values from an iterator range,
  341. * and updates first to point one past the last value consumed.
  342. */
  343. template<class It> rand48(It& first, It last) : lcf(first, last) { }
  344. // compiler-generated copy ctor and assignment operator are fine
  345. /** Seeds the generator with the default seed. */
  346. void seed() { seed(static_cast<uint32_t>(1)); }
  347. /**
  348. * Changes the current value x(n) of the generator to (x0 << 16) | 0x330e.
  349. */
  350. BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(rand48, result_type, x0)
  351. { lcf.seed(cnv(x0)); }
  352. /**
  353. * Seeds the generator using values from an iterator range,
  354. * and updates first to point one past the last value consumed.
  355. */
  356. template<class It> void seed(It& first, It last) { lcf.seed(first,last); }
  357. /**
  358. * Seeds the generator with values produced by @c seq.generate().
  359. */
  360. BOOST_RANDOM_DETAIL_SEED_SEQ_SEED(rand48, SeedSeq, seq)
  361. { lcf.seed(seq); }
  362. /** Returns the next value of the generator. */
  363. uint32_t operator()() { return static_cast<uint32_t>(lcf() >> 17); }
  364. /** Advances the state of the generator by @c z. */
  365. void discard(boost::uintmax_t z) { lcf.discard(z); }
  366. /** Fills a range with random values */
  367. template<class Iter>
  368. void generate(Iter first, Iter last)
  369. {
  370. for(; first != last; ++first) {
  371. *first = (*this)();
  372. }
  373. }
  374. #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
  375. /** Writes a @c rand48 to a @c std::ostream. */
  376. template<class CharT,class Traits>
  377. friend std::basic_ostream<CharT,Traits>&
  378. operator<<(std::basic_ostream<CharT,Traits>& os, const rand48& r)
  379. { os << r.lcf; return os; }
  380. /** Reads a @c rand48 from a @c std::istream. */
  381. template<class CharT,class Traits>
  382. friend std::basic_istream<CharT,Traits>&
  383. operator>>(std::basic_istream<CharT,Traits>& is, rand48& r)
  384. { is >> r.lcf; return is; }
  385. #endif
  386. /**
  387. * Returns true if the two generators will produce identical
  388. * sequences of values.
  389. */
  390. friend bool operator==(const rand48& x, const rand48& y)
  391. { return x.lcf == y.lcf; }
  392. /**
  393. * Returns true if the two generators will produce different
  394. * sequences of values.
  395. */
  396. friend bool operator!=(const rand48& x, const rand48& y)
  397. { return !(x == y); }
  398. private:
  399. /// \cond show_private
  400. typedef random::linear_congruential_engine<uint64_t,
  401. // xxxxULL is not portable
  402. uint64_t(0xDEECE66DUL) | (uint64_t(0x5) << 32),
  403. 0xB, uint64_t(1)<<48> lcf_t;
  404. lcf_t lcf;
  405. static boost::uint64_t cnv(boost::uint32_t x)
  406. { return (static_cast<uint64_t>(x) << 16) | 0x330e; }
  407. /// \endcond
  408. };
  409. #endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */
  410. } // namespace random
  411. using random::minstd_rand0;
  412. using random::minstd_rand;
  413. using random::rand48;
  414. } // namespace boost
  415. #include <boost/random/detail/enable_warnings.hpp>
  416. #endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP