1 /* boost random/uniform_int.hpp header file
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)
8 * See http://www.boost.org for most recent version including documentation.
10 * $Id: uniform_int.hpp 60755 2010-03-22 00:45:06Z steven_watanabe $
13 * 2001-04-08 added min<max assertion (N. Becker)
14 * 2001-02-18 moved to individual header files
17 #ifndef BOOST_RANDOM_UNIFORM_INT_HPP
18 #define BOOST_RANDOM_UNIFORM_INT_HPP
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>
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}.
37 * The template parameter IntType shall denote an integer-like value type.
39 template<class IntType = int>
43 typedef IntType input_type;
44 typedef IntType result_type;
46 /// \cond hide_private_members
47 typedef typename make_unsigned<result_type>::type range_type;
51 * Constructs a uniform_int object. @c min and @c max are
52 * the parameters of the distribution.
54 * Requires: min <= max
56 explicit uniform_int(IntType min_arg = 0, IntType max_arg = 9)
57 : _min(min_arg), _max(max_arg)
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);
63 assert(min_arg <= max_arg);
68 * Returns: The "min" parameter of the distribution
70 result_type min BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _min; }
72 * Returns: The "max" parameter of the distribution
74 result_type max BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _max; }
77 // can't have member function templates out-of-line due to MSVC bugs
78 template<class Engine>
79 result_type operator()(Engine& eng)
81 return generate(eng, _min, _max, _range);
84 template<class Engine>
85 result_type operator()(Engine& eng, result_type n)
94 return generate(eng, 0, n - 1, n - 1);
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)
102 os << ud._min << " " << ud._max;
106 template<class CharT, class Traits>
107 friend std::basic_istream<CharT,Traits>&
108 operator>>(std::basic_istream<CharT,Traits>& is, uniform_int& ud)
110 is >> std::ws >> ud._min >> std::ws >> ud._max;
119 #pragma warning(push)
120 // disable division by zero warning, since we can't
121 // actually divide by zero.
122 #pragma warning(disable:4723)
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)
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)());
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
146 // concatenate several invocations of the base RNG
147 // take extra care to avoid overflows
149 // limit == floor((range+1)/(brange+1))
150 // Therefore limit*(brange+1) <= range+1
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))
157 limit = (range+1)/(range_type(brange)+1);
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);
168 while(mult <= limit) {
169 // Postcondition: result <= range, thus no overflow
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)
179 // Postcondition: result < mult*(brange+1)
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);
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.
198 // Postcondition: mult <= range
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)
206 // Postcondition: result < mult
208 // See the second postcondition on the change to result.
209 mult *= range_type(brange)+range_type(1);
211 // loop postcondition: range/mult < brange+1
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)
223 // loop postcondition: (range/mult)*mult+(mult-1) >= range
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)
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.
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.
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.
253 return random::detail::add<range_type, result_type>()(result, min_value);
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
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)) {
267 bucket_size = (brange+1) / (static_cast<base_unsigned>(range)+1);
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);
287 _range = random::detail::subtract<result_type>()(_max, _min);
292 // The result_type may be signed or unsigned, but the _range is always
294 result_type _min, _max;
300 #endif // BOOST_RANDOM_UNIFORM_INT_HPP