]> git.donarmstrong.com Git - rsem.git/blob - boost/random/linear_congruential.hpp
351b9c19c8d98f90e0a97d35fed02513c469fd0e
[rsem.git] / boost / random / linear_congruential.hpp
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: linear_congruential.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $
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 <cassert>
21 #include <stdexcept>
22 #include <boost/config.hpp>
23 #include <boost/limits.hpp>
24 #include <boost/static_assert.hpp>
25 #include <boost/random/detail/config.hpp>
26 #include <boost/random/detail/const_mod.hpp>
27 #include <boost/detail/workaround.hpp>
28
29 #include <boost/random/detail/disable_warnings.hpp>
30
31 namespace boost {
32 namespace random {
33
34 /**
35  * Instantiations of class template linear_congruential model a
36  * \pseudo_random_number_generator. Linear congruential pseudo-random
37  * number generators are described in:
38  *
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  *
43  * Let x(n) denote the sequence of numbers returned by some pseudo-random
44  * number generator. Then for the linear congruential generator,
45  * x(n+1) := (a * x(n) + c) mod m. Parameters for the generator are
46  * x(0), a, c, m. The template parameter IntType shall denote an integral
47  * type. It must be large enough to hold values a, c, and m. The template
48  * parameters a and c must be smaller than m.
49  *
50  * Note: The quality of the generator crucially depends on the choice of
51  * the parameters. User code should use one of the sensibly parameterized
52  * generators such as minstd_rand instead.
53  */
54 template<class IntType, IntType a, IntType c, IntType m, IntType val>
55 class linear_congruential
56 {
57 public:
58   typedef IntType result_type;
59 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
60   static const bool has_fixed_range = true;
61   static const result_type min_value = ( c == 0 ? 1 : 0 );
62   static const result_type max_value = m-1;
63 #else
64   BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
65 #endif
66   BOOST_STATIC_CONSTANT(IntType, multiplier = a);
67   BOOST_STATIC_CONSTANT(IntType, increment = c);
68   BOOST_STATIC_CONSTANT(IntType, modulus = m);
69
70   // MSVC 6 and possibly others crash when encountering complicated integral
71   // constant expressions.  Avoid the check for now.
72   // BOOST_STATIC_ASSERT(m == 0 || a < m);
73   // BOOST_STATIC_ASSERT(m == 0 || c < m);
74
75   /**
76    * Constructs a linear_congruential generator, seeding it with @c x0.
77    */
78   explicit linear_congruential(IntType x0 = 1)
79   { 
80     seed(x0);
81
82     // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope
83 #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
84     BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
85 #endif
86   }
87
88   /**
89    * Constructs a @c linear_congruential generator 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(It& first, It last)
98   {
99       seed(first, last);
100   }
101
102   // compiler-generated copy constructor and assignment operator are fine
103
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   void seed(IntType x0 = 1)
111   {
112     // wrap _x if it doesn't fit in the destination
113     if(modulus == 0) {
114       _x = x0;
115     } else {
116       _x = x0 % modulus;
117     }
118     // handle negative seeds
119     if(_x <= 0 && _x != 0) {
120       _x += modulus;
121     }
122     // adjust to the correct range
123     if(increment == 0 && _x == 0) {
124       _x = 1;
125     }
126     assert(_x >= (min)());
127     assert(_x <= (max)());
128   }
129
130   /**
131    * seeds a @c linear_congruential generator with values taken
132    * from the itrator range [first, last) and adjusts @c first to
133    * point to the element after the last one used.  If there are
134    * not enough elements, throws @c std::invalid_argument.
135    *
136    * @c first and @c last must be input iterators.
137    */
138   template<class It>
139   void seed(It& first, It last)
140   {
141     if(first == last)
142       throw std::invalid_argument("linear_congruential::seed");
143     seed(*first++);
144   }
145
146   /**
147    * Returns the smallest value that the @c linear_congruential generator
148    * can produce.
149    */
150   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return c == 0 ? 1 : 0; }
151   /**
152    * Returns the largest value that the @c linear_congruential generator
153    * can produce.
154    */
155   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return modulus-1; }
156
157   /** Returns the next value of the @c linear_congruential generator. */
158   IntType operator()()
159   {
160     _x = const_mod<IntType, m>::mult_add(a, _x, c);
161     return _x;
162   }
163
164   static bool validation(IntType x) { return val == x; }
165
166 #ifdef BOOST_NO_OPERATORS_IN_NAMESPACE
167     
168   // Use a member function; Streamable concept not supported.
169   bool operator==(const linear_congruential& rhs) const
170   { return _x == rhs._x; }
171   bool operator!=(const linear_congruential& rhs) const
172   { return !(*this == rhs); }
173
174 #else 
175   friend bool operator==(const linear_congruential& x,
176                          const linear_congruential& y)
177   { return x._x == y._x; }
178   friend bool operator!=(const linear_congruential& x,
179                          const linear_congruential& y)
180   { return !(x == y); }
181     
182 #if !defined(BOOST_RANDOM_NO_STREAM_OPERATORS) && !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
183   template<class CharT, class Traits>
184   friend std::basic_ostream<CharT,Traits>&
185   operator<<(std::basic_ostream<CharT,Traits>& os,
186              const linear_congruential& lcg)
187   {
188     return os << lcg._x;
189   }
190
191   template<class CharT, class Traits>
192   friend std::basic_istream<CharT,Traits>&
193   operator>>(std::basic_istream<CharT,Traits>& is,
194              linear_congruential& lcg)
195   {
196     return is >> lcg._x;
197   }
198  
199 private:
200 #endif
201 #endif
202
203   IntType _x;
204 };
205
206 // probably needs the "no native streams" caveat for STLPort
207 #if !defined(__SGI_STL_PORT) && BOOST_WORKAROUND(__GNUC__, == 2)
208 template<class IntType, IntType a, IntType c, IntType m, IntType val>
209 std::ostream&
210 operator<<(std::ostream& os,
211            const linear_congruential<IntType,a,c,m,val>& lcg)
212 {
213     return os << lcg._x;
214 }
215
216 template<class IntType, IntType a, IntType c, IntType m, IntType val>
217 std::istream&
218 operator>>(std::istream& is,
219            linear_congruential<IntType,a,c,m,val>& lcg)
220 {
221     return is >> lcg._x;
222 }
223 #elif defined(BOOST_RANDOM_NO_STREAM_OPERATORS) || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x551))
224 template<class CharT, class Traits, class IntType, IntType a, IntType c, IntType m, IntType val>
225 std::basic_ostream<CharT,Traits>&
226 operator<<(std::basic_ostream<CharT,Traits>& os,
227            const linear_congruential<IntType,a,c,m,val>& lcg)
228 {
229     return os << lcg._x;
230 }
231
232 template<class CharT, class Traits, class IntType, IntType a, IntType c, IntType m, IntType val>
233 std::basic_istream<CharT,Traits>&
234 operator>>(std::basic_istream<CharT,Traits>& is,
235            linear_congruential<IntType,a,c,m,val>& lcg)
236 {
237     return is >> lcg._x;
238 }
239 #endif
240
241 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
242 //  A definition is required even for integral static constants
243 template<class IntType, IntType a, IntType c, IntType m, IntType val>
244 const bool linear_congruential<IntType, a, c, m, val>::has_fixed_range;
245 template<class IntType, IntType a, IntType c, IntType m, IntType val>
246 const typename linear_congruential<IntType, a, c, m, val>::result_type linear_congruential<IntType, a, c, m, val>::min_value;
247 template<class IntType, IntType a, IntType c, IntType m, IntType val>
248 const typename linear_congruential<IntType, a, c, m, val>::result_type linear_congruential<IntType, a, c, m, val>::max_value;
249 template<class IntType, IntType a, IntType c, IntType m, IntType val>
250 const IntType linear_congruential<IntType,a,c,m,val>::modulus;
251 #endif
252
253 } // namespace random
254
255 // validation values from the publications
256 /**
257  * The specialization \minstd_rand0 was originally suggested in
258  *
259  *  @blockquote
260  *  A pseudo-random number generator for the System/360, P.A. Lewis,
261  *  A.S. Goodman, J.M. Miller, IBM Systems Journal, Vol. 8, No. 2,
262  *  1969, pp. 136-146
263  *  @endblockquote
264  *
265  * It is examined more closely together with \minstd_rand in
266  *
267  *  @blockquote
268  *  "Random Number Generators: Good ones are hard to find",
269  *  Stephen K. Park and Keith W. Miller, Communications of
270  *  the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201 
271  *  @endblockquote
272  */
273 typedef random::linear_congruential<int32_t, 16807, 0, 2147483647, 
274   1043618065> minstd_rand0;
275
276 /** The specialization \minstd_rand was suggested in
277  *
278  *  @blockquote
279  *  "Random Number Generators: Good ones are hard to find",
280  *  Stephen K. Park and Keith W. Miller, Communications of
281  *  the ACM, Vol. 31, No. 10, October 1988, pp. 1192-1201
282  *  @endblockquote
283  */
284 typedef random::linear_congruential<int32_t, 48271, 0, 2147483647,
285   399268537> minstd_rand;
286
287
288 #if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
289 /** Class @c rand48 models a \pseudo_random_number_generator. It uses
290  * the linear congruential algorithm with the parameters a = 0x5DEECE66D,
291  * c = 0xB, m = 2**48. It delivers identical results to the @c lrand48()
292  * function available on some systems (assuming lcong48 has not been called).
293  *
294  * It is only available on systems where @c uint64_t is provided as an
295  * integral type, so that for example static in-class constants and/or
296  * enum definitions with large @c uint64_t numbers work.
297  */
298 class rand48 
299 {
300 public:
301   typedef int32_t result_type;
302 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
303   static const bool has_fixed_range = true;
304   static const int32_t min_value = 0;
305   static const int32_t max_value = integer_traits<int32_t>::const_max;
306 #else
307   enum { has_fixed_range = false };
308 #endif
309   /**
310    * Returns the smallest value that the generator can produce
311    */
312   int32_t min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }
313   /**
314    * Returns the largest value that the generator can produce
315    */
316   int32_t max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return std::numeric_limits<int32_t>::max BOOST_PREVENT_MACRO_SUBSTITUTION (); }
317   
318 #ifdef BOOST_RANDOM_DOXYGEN
319   /**
320    * If T is an integral type smaller than int46_t, constructs
321    * a \rand48 generator with x(0) := (x0 << 16) | 0x330e.  Otherwise
322    * constructs a \rand48 generator with x(0) = x0.
323    */
324   template<class T> explicit rand48(T x0 = 1);
325 #else
326   rand48() : lcf(cnv(static_cast<int32_t>(1))) {}
327   template<class T> explicit rand48(T x0) : lcf(cnv(x0)) { }
328 #endif
329   template<class It> rand48(It& first, It last) : lcf(first, last) { }
330
331   // compiler-generated copy ctor and assignment operator are fine
332
333 #ifdef BOOST_RANDOM_DOXYGEN
334   /**
335    * If T is an integral type smaller than int46_t, changes
336    * the current value x(n) of the generator to (x0 << 16) | 0x330e.
337    * Otherwise changes the current value x(n) to x0.
338    */
339   template<class T> void seed(T x0 = 1);
340 #else
341   void seed() { seed(static_cast<int32_t>(1)); }
342   template<class T> void seed(T x0) { lcf.seed(cnv(x0)); }
343 #endif
344   template<class It> void seed(It& first, It last) { lcf.seed(first,last); }
345
346   /**
347    * Returns the next value of the generator.
348    */
349   int32_t operator()() { return static_cast<int32_t>(lcf() >> 17); }
350   // by experiment from lrand48()
351   static bool validation(int32_t x) { return x == 1993516219; }
352
353 #ifndef BOOST_NO_OPERATORS_IN_NAMESPACE
354
355 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
356   template<class CharT,class Traits>
357   friend std::basic_ostream<CharT,Traits>&
358   operator<<(std::basic_ostream<CharT,Traits>& os, const rand48& r)
359   { os << r.lcf; return os; }
360
361   template<class CharT,class Traits>
362   friend std::basic_istream<CharT,Traits>&
363   operator>>(std::basic_istream<CharT,Traits>& is, rand48& r)
364   { is >> r.lcf; return is; }
365 #endif
366
367   friend bool operator==(const rand48& x, const rand48& y)
368   { return x.lcf == y.lcf; }
369   friend bool operator!=(const rand48& x, const rand48& y)
370   { return !(x == y); }
371 #else
372   // Use a member function; Streamable concept not supported.
373   bool operator==(const rand48& rhs) const
374   { return lcf == rhs.lcf; }
375   bool operator!=(const rand48& rhs) const
376   { return !(*this == rhs); }
377 #endif
378 private:
379   /// \cond hide_private_members
380   random::linear_congruential<uint64_t,
381     uint64_t(0xDEECE66DUL) | (uint64_t(0x5) << 32), // xxxxULL is not portable
382     0xB, uint64_t(1)<<48, /* unknown */ 0> lcf;
383   template<class T>
384   static uint64_t cnv(T x) 
385   {
386     if(sizeof(T) < sizeof(uint64_t)) {
387       return (static_cast<uint64_t>(x) << 16) | 0x330e;
388     } else {
389       return(static_cast<uint64_t>(x));
390     }
391   }
392   static uint64_t cnv(float x) { return(static_cast<uint64_t>(x)); }
393   static uint64_t cnv(double x) { return(static_cast<uint64_t>(x)); }
394   static uint64_t cnv(long double x) { return(static_cast<uint64_t>(x)); }
395   /// \endcond
396 };
397 #endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */
398
399 } // namespace boost
400
401 #include <boost/random/detail/enable_warnings.hpp>
402
403 #endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP