]> git.donarmstrong.com Git - rsem.git/blob - boost/random/uniform_int.hpp
426a9e1510581533437a2c794556833f112301c7
[rsem.git] / boost / random / uniform_int.hpp
1 /* boost random/uniform_int.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: uniform_int.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $
11  *
12  * Revision history
13  *  2001-04-08  added min<max assertion (N. Becker)
14  *  2001-02-18  moved to individual header files
15  */
16
17 #ifndef BOOST_RANDOM_UNIFORM_INT_HPP
18 #define BOOST_RANDOM_UNIFORM_INT_HPP
19
20 #include <cassert>
21 #include <iostream>
22 #include <boost/config.hpp>
23 #include <boost/limits.hpp>
24 #include <boost/static_assert.hpp>
25 #include <boost/detail/workaround.hpp>
26 #include <boost/random/detail/config.hpp>
27 #include <boost/random/detail/signed_unsigned_tools.hpp>
28 #include <boost/type_traits/make_unsigned.hpp>
29
30 namespace boost {
31
32 /**
33  * The distribution function uniform_int models a \random_distribution.
34  * On each invocation, it returns a random integer value uniformly
35  * distributed in the set of integer numbers {min, min+1, min+2, ..., max}.
36  *
37  * The template parameter IntType shall denote an integer-like value type.
38  */
39 template<class IntType = int>
40 class uniform_int
41 {
42 public:
43   typedef IntType input_type;
44   typedef IntType result_type;
45
46   /// \cond hide_private_members
47   typedef typename make_unsigned<result_type>::type range_type;
48   /// \endcond
49
50   /**
51    * Constructs a uniform_int object. @c min and @c max are
52    * the parameters of the distribution.
53    *
54    * Requires: min <= max
55    */
56   explicit uniform_int(IntType min_arg = 0, IntType max_arg = 9)
57     : _min(min_arg), _max(max_arg)
58   {
59 #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
60     // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope
61     BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
62 #endif
63     assert(min_arg <= max_arg);
64     init();
65   }
66
67   /**
68    * Returns: The "min" parameter of the distribution
69    */
70   result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _min; }
71   /**
72    * Returns: The "max" parameter of the distribution
73    */
74   result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _max; }
75   void reset() { }
76   
77   // can't have member function templates out-of-line due to MSVC bugs
78   template<class Engine>
79   result_type operator()(Engine& eng)
80   {
81       return generate(eng, _min, _max, _range);
82   }
83
84   template<class Engine>
85   result_type operator()(Engine& eng, result_type n)
86   {
87       assert(n > 0);
88
89       if (n == 1)
90       {
91         return 0;
92       }
93
94       return generate(eng, 0, n - 1, n - 1);
95   }
96
97 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
98   template<class CharT, class Traits>
99   friend std::basic_ostream<CharT,Traits>&
100   operator<<(std::basic_ostream<CharT,Traits>& os, const uniform_int& ud)
101   {
102     os << ud._min << " " << ud._max;
103     return os;
104   }
105
106   template<class CharT, class Traits>
107   friend std::basic_istream<CharT,Traits>&
108   operator>>(std::basic_istream<CharT,Traits>& is, uniform_int& ud)
109   {
110     is >> std::ws >> ud._min >> std::ws >> ud._max;
111     ud.init();
112     return is;
113   }
114 #endif
115
116 private:
117
118 #ifdef BOOST_MSVC
119 #pragma warning(push)
120 // disable division by zero warning, since we can't
121 // actually divide by zero.
122 #pragma warning(disable:4723)
123 #endif
124
125   /// \cond hide_private_members
126   template<class Engine>
127   static result_type generate(Engine& eng, result_type min_value, result_type /*max_value*/, range_type range)
128   {
129     typedef typename Engine::result_type base_result;
130     // ranges are always unsigned
131     typedef typename make_unsigned<base_result>::type base_unsigned;
132     const base_result bmin = (eng.min)();
133     const base_unsigned brange =
134       random::detail::subtract<base_result>()((eng.max)(), (eng.min)());
135
136     if(range == 0) {
137       return min_value;    
138     } else if(brange == range) {
139       // this will probably never happen in real life
140       // basically nothing to do; just take care we don't overflow / underflow
141       base_unsigned v = random::detail::subtract<base_result>()(eng(), bmin);
142       return random::detail::add<base_unsigned, result_type>()(v, min_value);
143     } else if(brange < range) {
144       // use rejection method to handle things like 0..3 --> 0..4
145       for(;;) {
146         // concatenate several invocations of the base RNG
147         // take extra care to avoid overflows
148
149         //  limit == floor((range+1)/(brange+1))
150         //  Therefore limit*(brange+1) <= range+1
151         range_type limit;
152         if(range == (std::numeric_limits<range_type>::max)()) {
153           limit = range/(range_type(brange)+1);
154           if(range % (range_type(brange)+1) == range_type(brange))
155             ++limit;
156         } else {
157           limit = (range+1)/(range_type(brange)+1);
158         }
159
160         // We consider "result" as expressed to base (brange+1):
161         // For every power of (brange+1), we determine a random factor
162         range_type result = range_type(0);
163         range_type mult = range_type(1);
164
165         // loop invariants:
166         //  result < mult
167         //  mult <= range
168         while(mult <= limit) {
169           // Postcondition: result <= range, thus no overflow
170           //
171           // limit*(brange+1)<=range+1                   def. of limit       (1)
172           // eng()-bmin<=brange                          eng() post.         (2)
173           // and mult<=limit.                            loop condition      (3)
174           // Therefore mult*(eng()-bmin+1)<=range+1      by (1),(2),(3)      (4)
175           // Therefore mult*(eng()-bmin)+mult<=range+1   rearranging (4)     (5)
176           // result<mult                                 loop invariant      (6)
177           // Therefore result+mult*(eng()-bmin)<range+1  by (5), (6)         (7)
178           //
179           // Postcondition: result < mult*(brange+1)
180           //
181           // result<mult                                 loop invariant      (1)
182           // eng()-bmin<=brange                          eng() post.         (2)
183           // Therefore result+mult*(eng()-bmin) <
184           //           mult+mult*(eng()-bmin)            by (1)              (3)
185           // Therefore result+(eng()-bmin)*mult <
186           //           mult+mult*brange                  by (2), (3)         (4)
187           // Therefore result+(eng()-bmin)*mult <
188           //           mult*(brange+1)                   by (4)
189           result += static_cast<range_type>(random::detail::subtract<base_result>()(eng(), bmin) * mult);
190
191           // equivalent to (mult * (brange+1)) == range+1, but avoids overflow.
192           if(mult * range_type(brange) == range - mult + 1) {
193               // The destination range is an integer power of
194               // the generator's range.
195               return(result);
196           }
197
198           // Postcondition: mult <= range
199           // 
200           // limit*(brange+1)<=range+1                   def. of limit       (1)
201           // mult<=limit                                 loop condition      (2)
202           // Therefore mult*(brange+1)<=range+1          by (1), (2)         (3)
203           // mult*(brange+1)!=range+1                    preceding if        (4)
204           // Therefore mult*(brange+1)<range+1           by (3), (4)         (5)
205           // 
206           // Postcondition: result < mult
207           //
208           // See the second postcondition on the change to result. 
209           mult *= range_type(brange)+range_type(1);
210         }
211         // loop postcondition: range/mult < brange+1
212         //
213         // mult > limit                                  loop condition      (1)
214         // Suppose range/mult >= brange+1                Assumption          (2)
215         // range >= mult*(brange+1)                      by (2)              (3)
216         // range+1 > mult*(brange+1)                     by (3)              (4)
217         // range+1 > (limit+1)*(brange+1)                by (1), (4)         (5)
218         // (range+1)/(brange+1) > limit+1                by (5)              (6)
219         // limit < floor((range+1)/(brange+1))           by (6)              (7)
220         // limit==floor((range+1)/(brange+1))            def. of limit       (8)
221         // not (2)                                       reductio            (9)
222         //
223         // loop postcondition: (range/mult)*mult+(mult-1) >= range
224         //
225         // (range/mult)*mult + range%mult == range       identity            (1)
226         // range%mult < mult                             def. of %           (2)
227         // (range/mult)*mult+mult > range                by (1), (2)         (3)
228         // (range/mult)*mult+(mult-1) >= range           by (3)              (4)
229         //
230         // Note that the maximum value of result at this point is (mult-1),
231         // so after this final step, we generate numbers that can be
232         // at least as large as range.  We have to really careful to avoid
233         // overflow in this final addition and in the rejection.  Anything
234         // that overflows is larger than range and can thus be rejected.
235
236         // range/mult < brange+1  -> no endless loop
237         range_type result_increment = uniform_int<range_type>(0, range/mult)(eng);
238         if((std::numeric_limits<range_type>::max)() / mult < result_increment) {
239           // The multiplcation would overflow.  Reject immediately.
240           continue;
241         }
242         result_increment *= mult;
243         // unsigned integers are guaranteed to wrap on overflow.
244         result += result_increment;
245         if(result < result_increment) {
246           // The addition overflowed.  Reject.
247           continue;
248         }
249         if(result > range) {
250           // Too big.  Reject.
251           continue;
252         }
253         return random::detail::add<range_type, result_type>()(result, min_value);
254       }
255     } else {                   // brange > range
256       base_unsigned bucket_size;
257       // it's safe to add 1 to range, as long as we cast it first,
258       // because we know that it is less than brange.  However,
259       // we do need to be careful not to cause overflow by adding 1
260       // to brange.
261       if(brange == (std::numeric_limits<base_unsigned>::max)()) {
262         bucket_size = brange / (static_cast<base_unsigned>(range)+1);
263         if(brange % (static_cast<base_unsigned>(range)+1) == static_cast<base_unsigned>(range)) {
264           ++bucket_size;
265         }
266       } else {
267         bucket_size = (brange+1) / (static_cast<base_unsigned>(range)+1);
268       }
269       for(;;) {
270         base_unsigned result =
271           random::detail::subtract<base_result>()(eng(), bmin);
272         result /= bucket_size;
273         // result and range are non-negative, and result is possibly larger
274         // than range, so the cast is safe
275         if(result <= static_cast<base_unsigned>(range))
276           return random::detail::add<base_unsigned, result_type>()(result, min_value);
277       }
278     }
279   }
280
281 #ifdef BOOST_MSVC
282 #pragma warning(pop)
283 #endif
284
285   void init()
286   {
287     _range = random::detail::subtract<result_type>()(_max, _min);
288   }
289
290   /// \endcond
291
292   // The result_type may be signed or unsigned, but the _range is always
293   // unsigned.
294   result_type _min, _max;
295   range_type _range;
296 };
297
298 } // namespace boost
299
300 #endif // BOOST_RANDOM_UNIFORM_INT_HPP