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