1 // Copyright 2017 The Abseil Authors.
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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.
15 #ifndef ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
16 #define ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
23 #include <type_traits>
27 #include "absl/random/bernoulli_distribution.h"
28 #include "absl/random/internal/iostream_state_saver.h"
29 #include "absl/random/uniform_int_distribution.h"
33 // absl::discrete_distribution
35 // A discrete distribution produces random integers i, where 0 <= i < n
36 // distributed according to the discrete probability function:
38 // P(i|p0,...,pn−1)=pi
40 // This class is an implementation of discrete_distribution (see
41 // [rand.dist.samp.discrete]).
43 // The algorithm used is Walker's Aliasing algorithm, described in Knuth, Vol 2.
44 // absl::discrete_distribution takes O(N) time to precompute the probabilities
45 // (where N is the number of possible outcomes in the distribution) at
46 // construction, and then takes O(1) time for each variate generation. Many
47 // other implementations also take O(N) time to construct an ordered sequence of
48 // partial sums, plus O(log N) time per variate to binary search.
50 template <typename IntType = int>
51 class discrete_distribution {
53 using result_type = IntType;
57 using distribution_type = discrete_distribution;
59 param_type() { init(); }
61 template <typename InputIterator>
62 explicit param_type(InputIterator begin, InputIterator end)
67 explicit param_type(std::initializer_list<double> weights) : p_(weights) {
71 template <class UnaryOperation>
72 explicit param_type(size_t nw, double xmin, double xmax,
76 double delta = (xmax - xmin) / static_cast<double>(nw);
78 double t = delta * 0.5;
79 for (size_t i = 0; i < nw; ++i) {
80 p_.push_back(fw(xmin + i * delta + t));
86 const std::vector<double>& probabilities() const { return p_; }
87 size_t n() const { return p_.size() - 1; }
89 friend bool operator==(const param_type& a, const param_type& b) {
90 return a.probabilities() == b.probabilities();
93 friend bool operator!=(const param_type& a, const param_type& b) {
98 friend class discrete_distribution;
102 std::vector<double> p_; // normalized probabilities
103 std::vector<std::pair<double, size_t>> q_; // (acceptance, alternate) pairs
105 static_assert(std::is_integral<result_type>::value,
106 "Class-template absl::discrete_distribution<> must be "
107 "parameterized using an integral type.");
110 discrete_distribution() : param_() {}
112 explicit discrete_distribution(const param_type& p) : param_(p) {}
114 template <typename InputIterator>
115 explicit discrete_distribution(InputIterator begin, InputIterator end)
116 : param_(begin, end) {}
118 explicit discrete_distribution(std::initializer_list<double> weights)
121 template <class UnaryOperation>
122 explicit discrete_distribution(size_t nw, double xmin, double xmax,
124 : param_(nw, xmin, xmax, std::move(fw)) {}
128 // generating functions
129 template <typename URBG>
130 result_type operator()(URBG& g) { // NOLINT(runtime/references)
131 return (*this)(g, param_);
134 template <typename URBG>
135 result_type operator()(URBG& g, // NOLINT(runtime/references)
136 const param_type& p);
138 const param_type& param() const { return param_; }
139 void param(const param_type& p) { param_ = p; }
141 result_type(min)() const { return 0; }
142 result_type(max)() const {
143 return static_cast<result_type>(param_.n());
146 // NOTE [rand.dist.sample.discrete] returns a std::vector<double> not a
147 // const std::vector<double>&.
148 const std::vector<double>& probabilities() const {
149 return param_.probabilities();
152 friend bool operator==(const discrete_distribution& a,
153 const discrete_distribution& b) {
154 return a.param_ == b.param_;
156 friend bool operator!=(const discrete_distribution& a,
157 const discrete_distribution& b) {
158 return a.param_ != b.param_;
165 // --------------------------------------------------------------------------
166 // Implementation details only below
167 // --------------------------------------------------------------------------
169 namespace random_internal {
171 // Using the vector `*probabilities`, whose values are the weights or
172 // probabilities of an element being selected, constructs the proportional
173 // probabilities used by the discrete distribution. `*probabilities` will be
174 // scaled, if necessary, so that its entries sum to a value sufficiently close
176 std::vector<std::pair<double, size_t>> InitDiscreteDistribution(
177 std::vector<double>* probabilities);
179 } // namespace random_internal
181 template <typename IntType>
182 void discrete_distribution<IntType>::param_type::init() {
185 q_.emplace_back(1.0, 0);
187 assert(n() <= (std::numeric_limits<IntType>::max)());
188 q_ = random_internal::InitDiscreteDistribution(&p_);
192 template <typename IntType>
193 template <typename URBG>
194 typename discrete_distribution<IntType>::result_type
195 discrete_distribution<IntType>::operator()(
196 URBG& g, // NOLINT(runtime/references)
197 const param_type& p) {
198 const auto idx = absl::uniform_int_distribution<result_type>(0, p.n())(g);
199 const auto& q = p.q_[idx];
200 const bool selected = absl::bernoulli_distribution(q.first)(g);
201 return selected ? idx : static_cast<result_type>(q.second);
204 template <typename CharT, typename Traits, typename IntType>
205 std::basic_ostream<CharT, Traits>& operator<<(
206 std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
207 const discrete_distribution<IntType>& x) {
208 auto saver = random_internal::make_ostream_state_saver(os);
209 const auto& probabilities = x.param().probabilities();
210 os << probabilities.size();
212 os.precision(random_internal::stream_precision_helper<double>::kPrecision);
213 for (const auto& p : probabilities) {
214 os << os.fill() << p;
219 template <typename CharT, typename Traits, typename IntType>
220 std::basic_istream<CharT, Traits>& operator>>(
221 std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
222 discrete_distribution<IntType>& x) { // NOLINT(runtime/references)
223 using param_type = typename discrete_distribution<IntType>::param_type;
224 auto saver = random_internal::make_istream_state_saver(is);
227 std::vector<double> p;
230 if (is.fail()) return is;
233 for (IntType i = 0; i < n && !is.fail(); ++i) {
234 auto tmp = random_internal::read_floating_point<double>(is);
235 if (is.fail()) return is;
239 x.param(param_type(p.begin(), p.end()));
245 #endif // ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_