]> git.donarmstrong.com Git - rsem.git/blob - boost/random/lagged_fibonacci.hpp
20860dae69156067a6292d173ff5591a51a7e4ae
[rsem.git] / boost / random / lagged_fibonacci.hpp
1 /* boost random/lagged_fibonacci.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: lagged_fibonacci.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_LAGGED_FIBONACCI_HPP
17 #define BOOST_RANDOM_LAGGED_FIBONACCI_HPP
18
19 #include <boost/config/no_tr1/cmath.hpp>
20 #include <iostream>
21 #include <algorithm>     // std::max
22 #include <iterator>
23 #include <boost/config/no_tr1/cmath.hpp>         // std::pow
24 #include <boost/config.hpp>
25 #include <boost/limits.hpp>
26 #include <boost/cstdint.hpp>
27 #include <boost/detail/workaround.hpp>
28 #include <boost/random/linear_congruential.hpp>
29 #include <boost/random/uniform_01.hpp>
30 #include <boost/random/detail/config.hpp>
31 #include <boost/random/detail/seed.hpp>
32 #include <boost/random/detail/pass_through_engine.hpp>
33
34 namespace boost {
35 namespace random {
36
37 #if BOOST_WORKAROUND(_MSC_FULL_VER, BOOST_TESTED_AT(13102292)) && BOOST_MSVC > 1300
38 #  define BOOST_RANDOM_EXTRACT_LF
39 #endif
40
41 #if defined(__APPLE_CC__) && defined(__GNUC__) && (__GNUC__ == 3) && (__GNUC_MINOR__ <= 3)
42 #  define BOOST_RANDOM_EXTRACT_LF
43 #endif
44
45 #  ifdef BOOST_RANDOM_EXTRACT_LF
46 namespace detail
47 {
48   template<class IStream, class F, class RealType>
49   IStream&
50   extract_lagged_fibonacci_01(
51       IStream& is
52       , F const& f
53       , unsigned int& i
54       , RealType* x
55       , RealType modulus)
56   {
57         is >> i >> std::ws;
58         for(unsigned int i = 0; i < f.long_lag; ++i)
59         {
60             RealType value;
61             is >> value >> std::ws;
62             x[i] = value / modulus;
63         }
64         return is;
65   }
66
67   template<class IStream, class F, class UIntType>
68   IStream&
69   extract_lagged_fibonacci(
70       IStream& is
71       , F const& f
72       , unsigned int& i
73       , UIntType* x)
74   {
75       is >> i >> std::ws;
76       for(unsigned int i = 0; i < f.long_lag; ++i)
77           is >> x[i] >> std::ws;
78       return is;
79   }
80 }
81 #  endif
82
83 /** 
84  * Instantiations of class template \lagged_fibonacci model a
85  * \pseudo_random_number_generator. It uses a lagged Fibonacci
86  * algorithm with two lags @c p and @c q:
87  * x(i) = x(i-p) + x(i-q) (mod 2<sup>w</sup>) with p > q.
88  */
89 template<class UIntType, int w, unsigned int p, unsigned int q,
90          UIntType val = 0>
91 class lagged_fibonacci
92 {
93 public:
94   typedef UIntType result_type;
95   BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
96   BOOST_STATIC_CONSTANT(int, word_size = w);
97   BOOST_STATIC_CONSTANT(unsigned int, long_lag = p);
98   BOOST_STATIC_CONSTANT(unsigned int, short_lag = q);
99
100   /**
101    * Returns: the smallest value that the generator can produce
102    */
103   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return 0; }
104   /**
105    * Returns: the largest value that the generator can produce
106    */
107   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return wordmask; }
108
109   /**
110    * Creates a new @c lagged_fibonacci generator and calls @c seed()
111    */
112   lagged_fibonacci() { init_wordmask(); seed(); }
113   /**
114    * Creates a new @c lagged_fibonacci generator and calls @c seed(value)
115    */
116   explicit lagged_fibonacci(uint32_t value) { init_wordmask(); seed(value); }
117   /**
118    * Creates a new @c lagged_fibonacci generator and calls @c seed(first, last)
119    */
120   template<class It> lagged_fibonacci(It& first, It last)
121   { init_wordmask(); seed(first, last); }
122   // compiler-generated copy ctor and assignment operator are fine
123
124 private:
125   /// \cond hide_private_members
126   void init_wordmask()
127   {
128     wordmask = 0;
129     for(int j = 0; j < w; ++j)
130       wordmask |= (1u << j);
131   }
132   /// \endcond
133
134 public:
135   /**
136    * Sets the state of the generator to values produced by
137    * a \minstd_rand generator.
138    */
139   void seed(uint32_t value = 331u)
140   {
141     minstd_rand0 gen(value);
142     for(unsigned int j = 0; j < long_lag; ++j)
143       x[j] = gen() & wordmask;
144     i = long_lag;
145   }
146
147   /**
148    * Sets the state of the generator to values from the iterator
149    * range [first, last).  If there are not enough elements in the
150    * range [first, last) throws @c std::invalid_argument.
151    */
152   template<class It>
153   void seed(It& first, It last)
154   {
155     // word size could be smaller than the seed values
156     unsigned int j;
157     for(j = 0; j < long_lag && first != last; ++j, ++first)
158       x[j] = *first & wordmask;
159     i = long_lag;
160     if(first == last && j < long_lag)
161       throw std::invalid_argument("lagged_fibonacci::seed");
162   }
163
164   /**
165    * Returns: the next value of the generator
166    */
167   result_type operator()()
168   {
169     if(i >= long_lag)
170       fill();
171     return x[i++];
172   }
173
174   static bool validation(result_type x)
175   {
176     return x == val;
177   }
178   
179 #ifndef BOOST_NO_OPERATORS_IN_NAMESPACE
180
181 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
182   template<class CharT, class Traits>
183   friend std::basic_ostream<CharT,Traits>&
184   operator<<(std::basic_ostream<CharT,Traits>& os, const lagged_fibonacci& f)
185   {
186     os << f.i << " ";
187     for(unsigned int i = 0; i < f.long_lag; ++i)
188       os << f.x[i] << " ";
189     return os;
190   }
191
192   template<class CharT, class Traits>
193   friend std::basic_istream<CharT, Traits>&
194   operator>>(std::basic_istream<CharT, Traits>& is, lagged_fibonacci& f)
195   {
196 # ifdef BOOST_RANDOM_EXTRACT_LF
197       return detail::extract_lagged_fibonacci(is, f, f.i, f.x);
198 # else
199       is >> f.i >> std::ws;
200       for(unsigned int i = 0; i < f.long_lag; ++i)
201           is >> f.x[i] >> std::ws;
202       return is;
203 # endif 
204   }
205 #endif
206
207   friend bool operator==(const lagged_fibonacci& x, const lagged_fibonacci& y)
208   { return x.i == y.i && std::equal(x.x, x.x+long_lag, y.x); }
209   friend bool operator!=(const lagged_fibonacci& x,
210                          const lagged_fibonacci& y)
211   { return !(x == y); }
212 #else
213   // Use a member function; Streamable concept not supported.
214   bool operator==(const lagged_fibonacci& rhs) const
215   { return i == rhs.i && std::equal(x, x+long_lag, rhs.x); }
216   bool operator!=(const lagged_fibonacci& rhs) const
217   { return !(*this == rhs); }
218 #endif
219
220 private:
221   /// \cond hide_private_members
222   void fill();
223   /// \endcond
224
225   UIntType wordmask;
226   unsigned int i;
227   UIntType x[long_lag];
228 };
229
230 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
231 //  A definition is required even for integral static constants
232 template<class UIntType, int w, unsigned int p, unsigned int q, UIntType val>
233 const bool lagged_fibonacci<UIntType, w, p, q, val>::has_fixed_range;
234 template<class UIntType, int w, unsigned int p, unsigned int q, UIntType val>
235 const unsigned int lagged_fibonacci<UIntType, w, p, q, val>::long_lag;
236 template<class UIntType, int w, unsigned int p, unsigned int q, UIntType val>
237 const unsigned int lagged_fibonacci<UIntType, w, p, q, val>::short_lag;
238 #endif
239
240 /// \cond hide_private_members
241
242 template<class UIntType, int w, unsigned int p, unsigned int q, UIntType val>
243 void lagged_fibonacci<UIntType, w, p, q, val>::fill()
244 {
245   // two loops to avoid costly modulo operations
246   {  // extra scope for MSVC brokenness w.r.t. for scope
247   for(unsigned int j = 0; j < short_lag; ++j)
248     x[j] = (x[j] + x[j+(long_lag-short_lag)]) & wordmask;
249   }
250   for(unsigned int j = short_lag; j < long_lag; ++j)
251     x[j] = (x[j] + x[j-short_lag]) & wordmask;
252   i = 0;
253 }
254
255
256
257 // lagged Fibonacci generator for the range [0..1)
258 // contributed by Matthias Troyer
259 // for p=55, q=24 originally by G. J. Mitchell and D. P. Moore 1958
260
261 template<class T, unsigned int p, unsigned int q>
262 struct fibonacci_validation
263 {
264   BOOST_STATIC_CONSTANT(bool, is_specialized = false);
265   static T value() { return 0; }
266   static T tolerance() { return 0; }
267 };
268
269 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
270 //  A definition is required even for integral static constants
271 template<class T, unsigned int p, unsigned int q>
272 const bool fibonacci_validation<T, p, q>::is_specialized;
273 #endif
274
275 #define BOOST_RANDOM_FIBONACCI_VAL(T,P,Q,V,E) \
276 template<> \
277 struct fibonacci_validation<T, P, Q>  \
278 {                                     \
279   BOOST_STATIC_CONSTANT(bool, is_specialized = true);     \
280   static T value() { return V; }      \
281   static T tolerance()                \
282 { return (std::max)(E, static_cast<T>(5*std::numeric_limits<T>::epsilon())); } \
283 };
284 // (The extra static_cast<T> in the std::max call above is actually
285 // unnecessary except for HP aCC 1.30, which claims that
286 // numeric_limits<double>::epsilon() doesn't actually return a double.)
287
288 BOOST_RANDOM_FIBONACCI_VAL(double, 607, 273, 0.4293817707235914, 1e-14)
289 BOOST_RANDOM_FIBONACCI_VAL(double, 1279, 418, 0.9421630240437659, 1e-14)
290 BOOST_RANDOM_FIBONACCI_VAL(double, 2281, 1252, 0.1768114046909004, 1e-14)
291 BOOST_RANDOM_FIBONACCI_VAL(double, 3217, 576, 0.1956232694868209, 1e-14)
292 BOOST_RANDOM_FIBONACCI_VAL(double, 4423, 2098, 0.9499762202147172, 1e-14)
293 BOOST_RANDOM_FIBONACCI_VAL(double, 9689, 5502, 0.05737836943695162, 1e-14)
294 BOOST_RANDOM_FIBONACCI_VAL(double, 19937, 9842, 0.5076528587449834, 1e-14)
295 BOOST_RANDOM_FIBONACCI_VAL(double, 23209, 13470, 0.5414473810619185, 1e-14)
296 BOOST_RANDOM_FIBONACCI_VAL(double, 44497,21034, 0.254135073399297, 1e-14)
297
298 #undef BOOST_RANDOM_FIBONACCI_VAL
299
300 /// \endcond
301
302 /**
303  * Instantiations of class template @c lagged_fibonacci_01 model a
304  * \pseudo_random_number_generator. It uses a lagged Fibonacci
305  * algorithm with two lags @c p and @c q, evaluated in floating-point
306  * arithmetic: x(i) = x(i-p) + x(i-q) (mod 1) with p > q. See
307  *
308  *  @blockquote
309  *  "Uniform random number generators for supercomputers", Richard Brent,
310  *  Proc. of Fifth Australian Supercomputer Conference, Melbourne,
311  *  Dec. 1992, pp. 704-706.
312  *  @endblockquote
313  *
314  * @xmlnote
315  * The quality of the generator crucially depends on the choice
316  * of the parameters. User code should employ one of the sensibly
317  * parameterized generators such as \lagged_fibonacci607 instead.
318  * @endxmlnote
319  *
320  * The generator requires considerable amounts of memory for the storage
321  * of its state array. For example, \lagged_fibonacci607 requires about
322  * 4856 bytes and \lagged_fibonacci44497 requires about 350 KBytes.
323  */
324 template<class RealType, int w, unsigned int p, unsigned int q>
325 class lagged_fibonacci_01
326 {
327 public:
328   typedef RealType result_type;
329   BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);
330   BOOST_STATIC_CONSTANT(int, word_size = w);
331   BOOST_STATIC_CONSTANT(unsigned int, long_lag = p);
332   BOOST_STATIC_CONSTANT(unsigned int, short_lag = q);
333
334   /** Constructs a @c lagged_fibonacci_01 generator and calls @c seed(). */
335   lagged_fibonacci_01() { init_modulus(); seed(); }
336   /** Constructs a @c lagged_fibonacci_01 generator and calls @c seed(value). */
337   BOOST_RANDOM_DETAIL_ARITHMETIC_CONSTRUCTOR(lagged_fibonacci_01, uint32_t, value)
338   { init_modulus(); seed(value); }
339   /** Constructs a @c lagged_fibonacci_01 generator and calls @c seed(gen). */
340   BOOST_RANDOM_DETAIL_GENERATOR_CONSTRUCTOR(lagged_fibonacci_01, Generator, gen)
341   { init_modulus(); seed(gen); }
342   template<class It> lagged_fibonacci_01(It& first, It last)
343   { init_modulus(); seed(first, last); }
344   // compiler-generated copy ctor and assignment operator are fine
345
346 private:
347   /// \cond hide_private_members
348   void init_modulus()
349   {
350 #ifndef BOOST_NO_STDC_NAMESPACE
351     // allow for Koenig lookup
352     using std::pow;
353 #endif
354     _modulus = pow(RealType(2), word_size);
355   }
356   /// \endcond
357
358 public:
359   /** Calls seed(331u). */
360   void seed() { seed(331u); }
361   /**
362    * Constructs a \minstd_rand0 generator with the constructor parameter
363    * value and calls seed with it. Distinct seeds in the range
364    * [1, 2147483647) will produce generators with different states. Other
365    * seeds will be equivalent to some seed within this range. See
366    * \linear_congruential for details.
367    */
368   BOOST_RANDOM_DETAIL_ARITHMETIC_SEED(lagged_fibonacci_01, uint32_t, value)
369   {
370     minstd_rand0 intgen(value);
371     seed(intgen);
372   }
373
374   /**
375    * Sets the state of this @c lagged_fibonacci_01 to the values returned
376    * by p invocations of \uniform_01<code>\<RealType\>()(gen)</code>.
377    *
378    * Complexity: Exactly p invocations of gen.
379    */
380   BOOST_RANDOM_DETAIL_GENERATOR_SEED(lagged_fibonacci, Generator, gen)
381   {
382     // use pass-by-reference, but wrap argument in pass_through_engine
383     typedef detail::pass_through_engine<Generator&> ref_gen;
384     uniform_01<ref_gen, RealType> gen01 =
385       uniform_01<ref_gen, RealType>(ref_gen(gen));
386     // I could have used std::generate_n, but it takes "gen" by value
387     for(unsigned int j = 0; j < long_lag; ++j)
388       x[j] = gen01();
389     i = long_lag;
390   }
391
392   template<class It>
393   void seed(It& first, It last)
394   {
395 #ifndef BOOST_NO_STDC_NAMESPACE
396     // allow for Koenig lookup
397     using std::fmod;
398     using std::pow;
399 #endif
400     unsigned long mask = ~((~0u) << (w%32));   // now lowest w bits set
401     RealType two32 = pow(RealType(2), 32);
402     unsigned int j;
403     for(j = 0; j < long_lag && first != last; ++j) {
404       x[j] = RealType(0);
405       for(int k = 0; k < w/32 && first != last; ++k, ++first)
406         x[j] += *first / pow(two32,k+1);
407       if(first != last && mask != 0) {
408         x[j] += fmod((*first & mask) / _modulus, RealType(1));
409         ++first;
410       }
411     }
412     i = long_lag;
413     if(first == last && j < long_lag)
414       throw std::invalid_argument("lagged_fibonacci_01::seed");
415   }
416
417   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return result_type(0); }
418   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return result_type(1); }
419
420   result_type operator()()
421   {
422     if(i >= long_lag)
423       fill();
424     return x[i++];
425   }
426
427   static bool validation(result_type x)
428   {
429     result_type v = fibonacci_validation<result_type, p, q>::value();
430     result_type epsilon = fibonacci_validation<result_type, p, q>::tolerance();
431     // std::abs is a source of trouble: sometimes, it's not overloaded
432     // for double, plus the usual namespace std noncompliance -> avoid it
433     // using std::abs;
434     // return abs(x - v) < 5 * epsilon
435     return x > v - epsilon && x < v + epsilon;
436   }
437   
438 #ifndef BOOST_NO_OPERATORS_IN_NAMESPACE
439
440 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
441   template<class CharT, class Traits>
442   friend std::basic_ostream<CharT,Traits>&
443   operator<<(std::basic_ostream<CharT,Traits>& os, const lagged_fibonacci_01&f)
444   {
445 #ifndef BOOST_NO_STDC_NAMESPACE
446     // allow for Koenig lookup
447     using std::pow;
448 #endif
449     os << f.i << " ";
450     std::ios_base::fmtflags oldflags = os.flags(os.dec | os.fixed | os.left); 
451     for(unsigned int i = 0; i < f.long_lag; ++i)
452       os << f.x[i] * f._modulus << " ";
453     os.flags(oldflags);
454     return os;
455   }
456
457   template<class CharT, class Traits>
458   friend std::basic_istream<CharT, Traits>&
459   operator>>(std::basic_istream<CharT, Traits>& is, lagged_fibonacci_01& f)
460     {
461 # ifdef BOOST_RANDOM_EXTRACT_LF
462         return detail::extract_lagged_fibonacci_01(is, f, f.i, f.x, f._modulus);
463 # else
464         is >> f.i >> std::ws;
465         for(unsigned int i = 0; i < f.long_lag; ++i) {
466             typename lagged_fibonacci_01::result_type value;
467             is >> value >> std::ws;
468             f.x[i] = value / f._modulus;
469         }
470         return is;
471 # endif 
472     }
473 #endif
474
475   friend bool operator==(const lagged_fibonacci_01& x,
476                          const lagged_fibonacci_01& y)
477   { return x.i == y.i && std::equal(x.x, x.x+long_lag, y.x); }
478   friend bool operator!=(const lagged_fibonacci_01& x,
479                          const lagged_fibonacci_01& y)
480   { return !(x == y); }
481 #else
482   // Use a member function; Streamable concept not supported.
483   bool operator==(const lagged_fibonacci_01& rhs) const
484   { return i == rhs.i && std::equal(x, x+long_lag, rhs.x); }
485   bool operator!=(const lagged_fibonacci_01& rhs) const
486   { return !(*this == rhs); }
487 #endif
488
489 private:
490   /// \cond hide_private_members
491   void fill();
492   /// \endcond
493   unsigned int i;
494   RealType x[long_lag];
495   RealType _modulus;
496 };
497
498 #ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION
499 //  A definition is required even for integral static constants
500 template<class RealType, int w, unsigned int p, unsigned int q>
501 const bool lagged_fibonacci_01<RealType, w, p, q>::has_fixed_range;
502 template<class RealType, int w, unsigned int p, unsigned int q>
503 const unsigned int lagged_fibonacci_01<RealType, w, p, q>::long_lag;
504 template<class RealType, int w, unsigned int p, unsigned int q>
505 const unsigned int lagged_fibonacci_01<RealType, w, p, q>::short_lag;
506 template<class RealType, int w, unsigned int p, unsigned int q>
507 const int lagged_fibonacci_01<RealType,w,p,q>::word_size;
508
509 #endif
510
511 /// \cond hide_private_members
512 template<class RealType, int w, unsigned int p, unsigned int q>
513 void lagged_fibonacci_01<RealType, w, p, q>::fill()
514 {
515   // two loops to avoid costly modulo operations
516   {  // extra scope for MSVC brokenness w.r.t. for scope
517   for(unsigned int j = 0; j < short_lag; ++j) {
518     RealType t = x[j] + x[j+(long_lag-short_lag)];
519     if(t >= RealType(1))
520       t -= RealType(1);
521     x[j] = t;
522   }
523   }
524   for(unsigned int j = short_lag; j < long_lag; ++j) {
525     RealType t = x[j] + x[j-short_lag];
526     if(t >= RealType(1))
527       t -= RealType(1);
528     x[j] = t;
529   }
530   i = 0;
531 }
532 /// \endcond
533
534 } // namespace random
535
536 #ifdef BOOST_RANDOM_DOXYGEN
537 namespace detail {
538 /**
539  * The specializations lagged_fibonacci607 ... lagged_fibonacci44497
540  * use well tested lags.
541  *
542  * See
543  *
544  *  @blockquote
545  *  "On the Periods of Generalized Fibonacci Recurrences", Richard P. Brent
546  *  Computer Sciences Laboratory Australian National University, December 1992
547  *  @endblockquote
548  *
549  * The lags used here can be found in
550  *
551  *  @blockquote
552  *  "Uniform random number generators for supercomputers", Richard Brent,
553  *  Proc. of Fifth Australian Supercomputer Conference, Melbourne,
554  *  Dec. 1992, pp. 704-706.
555  *  @endblockquote
556  */
557 struct lagged_fibonacci_doc {};
558 }
559 #endif
560
561 /**
562  * @copydoc boost::detail::lagged_fibonacci_doc
563  */
564 typedef random::lagged_fibonacci_01<double, 48, 607, 273> lagged_fibonacci607;
565 /**
566  * @copydoc boost::detail::lagged_fibonacci_doc
567  */
568 typedef random::lagged_fibonacci_01<double, 48, 1279, 418> lagged_fibonacci1279;
569 /**
570  * @copydoc boost::detail::lagged_fibonacci_doc
571  */
572 typedef random::lagged_fibonacci_01<double, 48, 2281, 1252> lagged_fibonacci2281;
573 /**
574  * @copydoc boost::detail::lagged_fibonacci_doc
575  */
576 typedef random::lagged_fibonacci_01<double, 48, 3217, 576> lagged_fibonacci3217;
577 /**
578  * @copydoc boost::detail::lagged_fibonacci_doc
579  */
580 typedef random::lagged_fibonacci_01<double, 48, 4423, 2098> lagged_fibonacci4423;
581 /**
582  * @copydoc boost::detail::lagged_fibonacci_doc
583  */
584 typedef random::lagged_fibonacci_01<double, 48, 9689, 5502> lagged_fibonacci9689;
585 /**
586  * @copydoc boost::detail::lagged_fibonacci_doc
587  */
588 typedef random::lagged_fibonacci_01<double, 48, 19937, 9842> lagged_fibonacci19937;
589 /**
590  * @copydoc boost::detail::lagged_fibonacci_doc
591  */
592 typedef random::lagged_fibonacci_01<double, 48, 23209, 13470> lagged_fibonacci23209;
593 /**
594  * @copydoc boost::detail::lagged_fibonacci_doc
595  */
596 typedef random::lagged_fibonacci_01<double, 48, 44497, 21034> lagged_fibonacci44497;
597
598
599 // It is possible to partially specialize uniform_01<> on lagged_fibonacci_01<>
600 // to help the compiler generate efficient code.  For GCC, this seems useless,
601 // because GCC optimizes (x-0)/(1-0) to (x-0).  This is good enough for now.
602
603 } // namespace boost
604
605 #endif // BOOST_RANDOM_LAGGED_FIBONACCI_HPP