uniform_int_distribution.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: uniform_int_distribution.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header defines a class for representing a uniform integer distribution
  20. // over the closed (inclusive) interval [a,b]. You use this distribution in
  21. // combination with an Abseil random bit generator to produce random values
  22. // according to the rules of the distribution.
  23. //
  24. // `y_absl::uniform_int_distribution` is a drop-in replacement for the C++11
  25. // `std::uniform_int_distribution` [rand.dist.uni.int] but is considerably
  26. // faster than the libstdc++ implementation.
  27. #ifndef Y_ABSL_RANDOM_UNIFORM_INT_DISTRIBUTION_H_
  28. #define Y_ABSL_RANDOM_UNIFORM_INT_DISTRIBUTION_H_
  29. #include <cassert>
  30. #include <istream>
  31. #include <limits>
  32. #include <type_traits>
  33. #include "y_absl/base/optimization.h"
  34. #include "y_absl/random/internal/fast_uniform_bits.h"
  35. #include "y_absl/random/internal/iostream_state_saver.h"
  36. #include "y_absl/random/internal/traits.h"
  37. #include "y_absl/random/internal/wide_multiply.h"
  38. namespace y_absl {
  39. Y_ABSL_NAMESPACE_BEGIN
  40. // y_absl::uniform_int_distribution<T>
  41. //
  42. // This distribution produces random integer values uniformly distributed in the
  43. // closed (inclusive) interval [a, b].
  44. //
  45. // Example:
  46. //
  47. // y_absl::BitGen gen;
  48. //
  49. // // Use the distribution to produce a value between 1 and 6, inclusive.
  50. // int die_roll = y_absl::uniform_int_distribution<int>(1, 6)(gen);
  51. //
  52. template <typename IntType = int>
  53. class uniform_int_distribution {
  54. private:
  55. using unsigned_type =
  56. typename random_internal::make_unsigned_bits<IntType>::type;
  57. public:
  58. using result_type = IntType;
  59. class param_type {
  60. public:
  61. using distribution_type = uniform_int_distribution;
  62. explicit param_type(
  63. result_type lo = 0,
  64. result_type hi = (std::numeric_limits<result_type>::max)())
  65. : lo_(lo),
  66. range_(static_cast<unsigned_type>(hi) -
  67. static_cast<unsigned_type>(lo)) {
  68. // [rand.dist.uni.int] precondition 2
  69. assert(lo <= hi);
  70. }
  71. result_type a() const { return lo_; }
  72. result_type b() const {
  73. return static_cast<result_type>(static_cast<unsigned_type>(lo_) + range_);
  74. }
  75. friend bool operator==(const param_type& a, const param_type& b) {
  76. return a.lo_ == b.lo_ && a.range_ == b.range_;
  77. }
  78. friend bool operator!=(const param_type& a, const param_type& b) {
  79. return !(a == b);
  80. }
  81. private:
  82. friend class uniform_int_distribution;
  83. unsigned_type range() const { return range_; }
  84. result_type lo_;
  85. unsigned_type range_;
  86. static_assert(random_internal::IsIntegral<result_type>::value,
  87. "Class-template y_absl::uniform_int_distribution<> must be "
  88. "parameterized using an integral type.");
  89. }; // param_type
  90. uniform_int_distribution() : uniform_int_distribution(0) {}
  91. explicit uniform_int_distribution(
  92. result_type lo,
  93. result_type hi = (std::numeric_limits<result_type>::max)())
  94. : param_(lo, hi) {}
  95. explicit uniform_int_distribution(const param_type& param) : param_(param) {}
  96. // uniform_int_distribution<T>::reset()
  97. //
  98. // Resets the uniform int distribution. Note that this function has no effect
  99. // because the distribution already produces independent values.
  100. void reset() {}
  101. template <typename URBG>
  102. result_type operator()(URBG& gen) { // NOLINT(runtime/references)
  103. return (*this)(gen, param());
  104. }
  105. template <typename URBG>
  106. result_type operator()(
  107. URBG& gen, const param_type& param) { // NOLINT(runtime/references)
  108. return static_cast<result_type>(param.a() + Generate(gen, param.range()));
  109. }
  110. result_type a() const { return param_.a(); }
  111. result_type b() const { return param_.b(); }
  112. param_type param() const { return param_; }
  113. void param(const param_type& params) { param_ = params; }
  114. result_type(min)() const { return a(); }
  115. result_type(max)() const { return b(); }
  116. friend bool operator==(const uniform_int_distribution& a,
  117. const uniform_int_distribution& b) {
  118. return a.param_ == b.param_;
  119. }
  120. friend bool operator!=(const uniform_int_distribution& a,
  121. const uniform_int_distribution& b) {
  122. return !(a == b);
  123. }
  124. private:
  125. // Generates a value in the *closed* interval [0, R]
  126. template <typename URBG>
  127. unsigned_type Generate(URBG& g, // NOLINT(runtime/references)
  128. unsigned_type R);
  129. param_type param_;
  130. };
  131. // -----------------------------------------------------------------------------
  132. // Implementation details follow
  133. // -----------------------------------------------------------------------------
  134. template <typename CharT, typename Traits, typename IntType>
  135. std::basic_ostream<CharT, Traits>& operator<<(
  136. std::basic_ostream<CharT, Traits>& os,
  137. const uniform_int_distribution<IntType>& x) {
  138. using stream_type =
  139. typename random_internal::stream_format_type<IntType>::type;
  140. auto saver = random_internal::make_ostream_state_saver(os);
  141. os << static_cast<stream_type>(x.a()) << os.fill()
  142. << static_cast<stream_type>(x.b());
  143. return os;
  144. }
  145. template <typename CharT, typename Traits, typename IntType>
  146. std::basic_istream<CharT, Traits>& operator>>(
  147. std::basic_istream<CharT, Traits>& is,
  148. uniform_int_distribution<IntType>& x) {
  149. using param_type = typename uniform_int_distribution<IntType>::param_type;
  150. using result_type = typename uniform_int_distribution<IntType>::result_type;
  151. using stream_type =
  152. typename random_internal::stream_format_type<IntType>::type;
  153. stream_type a;
  154. stream_type b;
  155. auto saver = random_internal::make_istream_state_saver(is);
  156. is >> a >> b;
  157. if (!is.fail()) {
  158. x.param(
  159. param_type(static_cast<result_type>(a), static_cast<result_type>(b)));
  160. }
  161. return is;
  162. }
  163. template <typename IntType>
  164. template <typename URBG>
  165. typename random_internal::make_unsigned_bits<IntType>::type
  166. uniform_int_distribution<IntType>::Generate(
  167. URBG& g, // NOLINT(runtime/references)
  168. typename random_internal::make_unsigned_bits<IntType>::type R) {
  169. random_internal::FastUniformBits<unsigned_type> fast_bits;
  170. unsigned_type bits = fast_bits(g);
  171. const unsigned_type Lim = R + 1;
  172. if ((R & Lim) == 0) {
  173. // If the interval's length is a power of two range, just take the low bits.
  174. return bits & R;
  175. }
  176. // Generates a uniform variate on [0, Lim) using fixed-point multiplication.
  177. // The above fast-path guarantees that Lim is representable in unsigned_type.
  178. //
  179. // Algorithm adapted from
  180. // http://lemire.me/blog/2016/06/30/fast-random-shuffling/, with added
  181. // explanation.
  182. //
  183. // The algorithm creates a uniform variate `bits` in the interval [0, 2^N),
  184. // and treats it as the fractional part of a fixed-point real value in [0, 1),
  185. // multiplied by 2^N. For example, 0.25 would be represented as 2^(N - 2),
  186. // because 2^N * 0.25 == 2^(N - 2).
  187. //
  188. // Next, `bits` and `Lim` are multiplied with a wide-multiply to bring the
  189. // value into the range [0, Lim). The integral part (the high word of the
  190. // multiplication result) is then very nearly the desired result. However,
  191. // this is not quite accurate; viewing the multiplication result as one
  192. // double-width integer, the resulting values for the sample are mapped as
  193. // follows:
  194. //
  195. // If the result lies in this interval: Return this value:
  196. // [0, 2^N) 0
  197. // [2^N, 2 * 2^N) 1
  198. // ... ...
  199. // [K * 2^N, (K + 1) * 2^N) K
  200. // ... ...
  201. // [(Lim - 1) * 2^N, Lim * 2^N) Lim - 1
  202. //
  203. // While all of these intervals have the same size, the result of `bits * Lim`
  204. // must be a multiple of `Lim`, and not all of these intervals contain the
  205. // same number of multiples of `Lim`. In particular, some contain
  206. // `F = floor(2^N / Lim)` and some contain `F + 1 = ceil(2^N / Lim)`. This
  207. // difference produces a small nonuniformity, which is corrected by applying
  208. // rejection sampling to one of the values in the "larger intervals" (i.e.,
  209. // the intervals containing `F + 1` multiples of `Lim`.
  210. //
  211. // An interval contains `F + 1` multiples of `Lim` if and only if its smallest
  212. // value modulo 2^N is less than `2^N % Lim`. The unique value satisfying
  213. // this property is used as the one for rejection. That is, a value of
  214. // `bits * Lim` is rejected if `(bit * Lim) % 2^N < (2^N % Lim)`.
  215. using helper = random_internal::wide_multiply<unsigned_type>;
  216. auto product = helper::multiply(bits, Lim);
  217. // Two optimizations here:
  218. // * Rejection occurs with some probability less than 1/2, and for reasonable
  219. // ranges considerably less (in particular, less than 1/(F+1)), so
  220. // Y_ABSL_PREDICT_FALSE is apt.
  221. // * `Lim` is an overestimate of `threshold`, and doesn't require a divide.
  222. if (Y_ABSL_PREDICT_FALSE(helper::lo(product) < Lim)) {
  223. // This quantity is exactly equal to `2^N % Lim`, but does not require high
  224. // precision calculations: `2^N % Lim` is congruent to `(2^N - Lim) % Lim`.
  225. // Ideally this could be expressed simply as `-X` rather than `2^N - X`, but
  226. // for types smaller than int, this calculation is incorrect due to integer
  227. // promotion rules.
  228. const unsigned_type threshold =
  229. ((std::numeric_limits<unsigned_type>::max)() - Lim + 1) % Lim;
  230. while (helper::lo(product) < threshold) {
  231. bits = fast_bits(g);
  232. product = helper::multiply(bits, Lim);
  233. }
  234. }
  235. return helper::hi(product);
  236. }
  237. Y_ABSL_NAMESPACE_END
  238. } // namespace y_absl
  239. #endif // Y_ABSL_RANDOM_UNIFORM_INT_DISTRIBUTION_H_