linear_congruential.hpp 16 KB

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