log_uniform_int_distribution.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. #ifndef ABSL_RANDOM_LOG_UNIFORM_INT_DISTRIBUTION_H_
  15. #define ABSL_RANDOM_LOG_UNIFORM_INT_DISTRIBUTION_H_
  16. #include <algorithm>
  17. #include <cassert>
  18. #include <cmath>
  19. #include <istream>
  20. #include <limits>
  21. #include <ostream>
  22. #include <type_traits>
  23. #include "absl/numeric/bits.h"
  24. #include "absl/random/internal/fastmath.h"
  25. #include "absl/random/internal/generate_real.h"
  26. #include "absl/random/internal/iostream_state_saver.h"
  27. #include "absl/random/internal/traits.h"
  28. #include "absl/random/uniform_int_distribution.h"
  29. namespace absl {
  30. ABSL_NAMESPACE_BEGIN
  31. // log_uniform_int_distribution:
  32. //
  33. // Returns a random variate R in range [min, max] such that
  34. // floor(log(R-min, base)) is uniformly distributed.
  35. // We ensure uniformity by discretization using the
  36. // boundary sets [0, 1, base, base * base, ... min(base*n, max)]
  37. //
  38. template <typename IntType = int>
  39. class log_uniform_int_distribution {
  40. private:
  41. using unsigned_type =
  42. typename random_internal::make_unsigned_bits<IntType>::type;
  43. public:
  44. using result_type = IntType;
  45. class param_type {
  46. public:
  47. using distribution_type = log_uniform_int_distribution;
  48. explicit param_type(
  49. result_type min = 0,
  50. result_type max = (std::numeric_limits<result_type>::max)(),
  51. result_type base = 2)
  52. : min_(min),
  53. max_(max),
  54. base_(base),
  55. range_(static_cast<unsigned_type>(max_) -
  56. static_cast<unsigned_type>(min_)),
  57. log_range_(0) {
  58. assert(max_ >= min_);
  59. assert(base_ > 1);
  60. if (base_ == 2) {
  61. // Determine where the first set bit is on range(), giving a log2(range)
  62. // value which can be used to construct bounds.
  63. log_range_ = (std::min)(random_internal::BitWidth(range()),
  64. std::numeric_limits<unsigned_type>::digits);
  65. } else {
  66. // NOTE: Computing the logN(x) introduces error from 2 sources:
  67. // 1. Conversion of int to double loses precision for values >=
  68. // 2^53, which may cause some log() computations to operate on
  69. // different values.
  70. // 2. The error introduced by the division will cause the result
  71. // to differ from the expected value.
  72. //
  73. // Thus a result which should equal K may equal K +/- epsilon,
  74. // which can eliminate some values depending on where the bounds fall.
  75. const double inv_log_base = 1.0 / std::log(static_cast<double>(base_));
  76. const double log_range = std::log(static_cast<double>(range()) + 0.5);
  77. log_range_ = static_cast<int>(std::ceil(inv_log_base * log_range));
  78. }
  79. }
  80. result_type(min)() const { return min_; }
  81. result_type(max)() const { return max_; }
  82. result_type base() const { return base_; }
  83. friend bool operator==(const param_type& a, const param_type& b) {
  84. return a.min_ == b.min_ && a.max_ == b.max_ && a.base_ == b.base_;
  85. }
  86. friend bool operator!=(const param_type& a, const param_type& b) {
  87. return !(a == b);
  88. }
  89. private:
  90. friend class log_uniform_int_distribution;
  91. int log_range() const { return log_range_; }
  92. unsigned_type range() const { return range_; }
  93. result_type min_;
  94. result_type max_;
  95. result_type base_;
  96. unsigned_type range_; // max - min
  97. int log_range_; // ceil(logN(range_))
  98. static_assert(random_internal::IsIntegral<IntType>::value,
  99. "Class-template absl::log_uniform_int_distribution<> must be "
  100. "parameterized using an integral type.");
  101. };
  102. log_uniform_int_distribution() : log_uniform_int_distribution(0) {}
  103. explicit log_uniform_int_distribution(
  104. result_type min,
  105. result_type max = (std::numeric_limits<result_type>::max)(),
  106. result_type base = 2)
  107. : param_(min, max, base) {}
  108. explicit log_uniform_int_distribution(const param_type& p) : param_(p) {}
  109. void reset() {}
  110. // generating functions
  111. template <typename URBG>
  112. result_type operator()(URBG& g) { // NOLINT(runtime/references)
  113. return (*this)(g, param_);
  114. }
  115. template <typename URBG>
  116. result_type operator()(URBG& g, // NOLINT(runtime/references)
  117. const param_type& p) {
  118. return static_cast<result_type>((p.min)() + Generate(g, p));
  119. }
  120. result_type(min)() const { return (param_.min)(); }
  121. result_type(max)() const { return (param_.max)(); }
  122. result_type base() const { return param_.base(); }
  123. param_type param() const { return param_; }
  124. void param(const param_type& p) { param_ = p; }
  125. friend bool operator==(const log_uniform_int_distribution& a,
  126. const log_uniform_int_distribution& b) {
  127. return a.param_ == b.param_;
  128. }
  129. friend bool operator!=(const log_uniform_int_distribution& a,
  130. const log_uniform_int_distribution& b) {
  131. return a.param_ != b.param_;
  132. }
  133. private:
  134. // Returns a log-uniform variate in the range [0, p.range()]. The caller
  135. // should add min() to shift the result to the correct range.
  136. template <typename URNG>
  137. unsigned_type Generate(URNG& g, // NOLINT(runtime/references)
  138. const param_type& p);
  139. param_type param_;
  140. };
  141. template <typename IntType>
  142. template <typename URBG>
  143. typename log_uniform_int_distribution<IntType>::unsigned_type
  144. log_uniform_int_distribution<IntType>::Generate(
  145. URBG& g, // NOLINT(runtime/references)
  146. const param_type& p) {
  147. // sample e over [0, log_range]. Map the results of e to this:
  148. // 0 => 0
  149. // 1 => [1, b-1]
  150. // 2 => [b, (b^2)-1]
  151. // n => [b^(n-1)..(b^n)-1]
  152. const int e = absl::uniform_int_distribution<int>(0, p.log_range())(g);
  153. if (e == 0) {
  154. return 0;
  155. }
  156. const int d = e - 1;
  157. unsigned_type base_e, top_e;
  158. if (p.base() == 2) {
  159. base_e = static_cast<unsigned_type>(1) << d;
  160. top_e = (e >= std::numeric_limits<unsigned_type>::digits)
  161. ? (std::numeric_limits<unsigned_type>::max)()
  162. : (static_cast<unsigned_type>(1) << e) - 1;
  163. } else {
  164. const double r = std::pow(static_cast<double>(p.base()), d);
  165. const double s = (r * static_cast<double>(p.base())) - 1.0;
  166. base_e =
  167. (r > static_cast<double>((std::numeric_limits<unsigned_type>::max)()))
  168. ? (std::numeric_limits<unsigned_type>::max)()
  169. : static_cast<unsigned_type>(r);
  170. top_e =
  171. (s > static_cast<double>((std::numeric_limits<unsigned_type>::max)()))
  172. ? (std::numeric_limits<unsigned_type>::max)()
  173. : static_cast<unsigned_type>(s);
  174. }
  175. const unsigned_type lo = (base_e >= p.range()) ? p.range() : base_e;
  176. const unsigned_type hi = (top_e >= p.range()) ? p.range() : top_e;
  177. // choose uniformly over [lo, hi]
  178. return absl::uniform_int_distribution<result_type>(
  179. static_cast<result_type>(lo), static_cast<result_type>(hi))(g);
  180. }
  181. template <typename CharT, typename Traits, typename IntType>
  182. std::basic_ostream<CharT, Traits>& operator<<(
  183. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  184. const log_uniform_int_distribution<IntType>& x) {
  185. using stream_type =
  186. typename random_internal::stream_format_type<IntType>::type;
  187. auto saver = random_internal::make_ostream_state_saver(os);
  188. os << static_cast<stream_type>((x.min)()) << os.fill()
  189. << static_cast<stream_type>((x.max)()) << os.fill()
  190. << static_cast<stream_type>(x.base());
  191. return os;
  192. }
  193. template <typename CharT, typename Traits, typename IntType>
  194. std::basic_istream<CharT, Traits>& operator>>(
  195. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  196. log_uniform_int_distribution<IntType>& x) { // NOLINT(runtime/references)
  197. using param_type = typename log_uniform_int_distribution<IntType>::param_type;
  198. using result_type =
  199. typename log_uniform_int_distribution<IntType>::result_type;
  200. using stream_type =
  201. typename random_internal::stream_format_type<IntType>::type;
  202. stream_type min;
  203. stream_type max;
  204. stream_type base;
  205. auto saver = random_internal::make_istream_state_saver(is);
  206. is >> min >> max >> base;
  207. if (!is.fail()) {
  208. x.param(param_type(static_cast<result_type>(min),
  209. static_cast<result_type>(max),
  210. static_cast<result_type>(base)));
  211. }
  212. return is;
  213. }
  214. ABSL_NAMESPACE_END
  215. } // namespace absl
  216. #endif // ABSL_RANDOM_LOG_UNIFORM_INT_DISTRIBUTION_H_