1 /* boost random/uniform_smallint.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.
13 * 2001-04-08 added min<max assertion (N. Becker)
14 * 2001-02-18 moved to individual header files
17 #ifndef BOOST_RANDOM_UNIFORM_SMALLINT_HPP
18 #define BOOST_RANDOM_UNIFORM_SMALLINT_HPP
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/uniform_01.hpp>
27 #include <boost/detail/workaround.hpp>
31 // uniform integer distribution on a small range [min, max]
33 template<class IntType
= int>
34 class uniform_smallint
37 typedef IntType input_type
;
38 typedef IntType result_type
;
40 explicit uniform_smallint(IntType min_arg
= 0, IntType max_arg
= 9)
41 : _min(min_arg
), _max(max_arg
)
43 #ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
44 // MSVC fails BOOST_STATIC_ASSERT with std::numeric_limits at class scope
45 BOOST_STATIC_ASSERT(std::numeric_limits
<IntType
>::is_integer
);
49 result_type min
BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _min
; }
50 result_type max
BOOST_PREVENT_MACRO_SUBSTITUTION () const { return _max
; }
53 template<class Engine
>
54 result_type
operator()(Engine
& eng
)
56 typedef typename
Engine::result_type base_result
;
57 base_result _range
= static_cast<base_result
>(_max
-_min
)+1;
58 base_result _factor
= 1;
60 // LCGs get bad when only taking the low bits.
61 // (probably put this logic into a partial template specialization)
62 // Check how many low bits we can ignore before we get too much
63 // quantization error.
64 base_result r_base
= (eng
.max
)() - (eng
.min
)();
65 if(r_base
== (std::numeric_limits
<base_result
>::max
)()) {
70 if(r_base
% _range
== 0) {
71 // No quantization effects, good
72 _factor
= r_base
/ _range
;
74 // carefully avoid overflow; pessimizing here
75 for( ; r_base
/_range
/32 >= _range
; _factor
*= 2)
79 return ((eng() - (eng
.min
)()) / _factor
) % _range
+ _min
;
82 #ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
83 template<class CharT
, class Traits
>
84 friend std::basic_ostream
<CharT
,Traits
>&
85 operator<<(std::basic_ostream
<CharT
,Traits
>& os
, const uniform_smallint
& ud
)
87 os
<< ud
._min
<< " " << ud
._max
;
91 template<class CharT
, class Traits
>
92 friend std::basic_istream
<CharT
,Traits
>&
93 operator>>(std::basic_istream
<CharT
,Traits
>& is
, uniform_smallint
& ud
)
95 is
>> std::ws
>> ud
._min
>> std::ws
>> ud
._max
;
108 #endif // BOOST_RANDOM_UNIFORM_SMALLINT_HPP