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_BERNOULLI_DISTRIBUTION_H_
16 #define ABSL_RANDOM_BERNOULLI_DISTRIBUTION_H_
17
18 #include <cstdint>
19 #include <istream>
20 #include <limits>
21
22 #include "absl/base/optimization.h"
23 #include "absl/random/internal/fast_uniform_bits.h"
24 #include "absl/random/internal/iostream_state_saver.h"
25
26 namespace absl {
27 ABSL_NAMESPACE_BEGIN
28
29 // absl::bernoulli_distribution is a drop in replacement for
30 // std::bernoulli_distribution. It guarantees that (given a perfect
31 // UniformRandomBitGenerator) the acceptance probability is *exactly* equal to
32 // the given double.
33 //
34 // The implementation assumes that double is IEEE754
35 class bernoulli_distribution {
36 public:
37 using result_type = bool;
38
39 class param_type {
40 public:
41 using distribution_type = bernoulli_distribution;
42
prob_(p)43 explicit param_type(double p = 0.5) : prob_(p) {
44 assert(p >= 0.0 && p <= 1.0);
45 }
46
p()47 double p() const { return prob_; }
48
49 friend bool operator==(const param_type& p1, const param_type& p2) {
50 return p1.p() == p2.p();
51 }
52 friend bool operator!=(const param_type& p1, const param_type& p2) {
53 return p1.p() != p2.p();
54 }
55
56 private:
57 double prob_;
58 };
59
bernoulli_distribution()60 bernoulli_distribution() : bernoulli_distribution(0.5) {}
61
bernoulli_distribution(double p)62 explicit bernoulli_distribution(double p) : param_(p) {}
63
bernoulli_distribution(param_type p)64 explicit bernoulli_distribution(param_type p) : param_(p) {}
65
66 // no-op
reset()67 void reset() {}
68
69 template <typename URBG>
operator()70 bool operator()(URBG& g) { // NOLINT(runtime/references)
71 return Generate(param_.p(), g);
72 }
73
74 template <typename URBG>
operator()75 bool operator()(URBG& g, // NOLINT(runtime/references)
76 const param_type& param) {
77 return Generate(param.p(), g);
78 }
79
param()80 param_type param() const { return param_; }
param(const param_type & param)81 void param(const param_type& param) { param_ = param; }
82
p()83 double p() const { return param_.p(); }
84
result_type(min)85 result_type(min)() const { return false; }
result_type(max)86 result_type(max)() const { return true; }
87
88 friend bool operator==(const bernoulli_distribution& d1,
89 const bernoulli_distribution& d2) {
90 return d1.param_ == d2.param_;
91 }
92
93 friend bool operator!=(const bernoulli_distribution& d1,
94 const bernoulli_distribution& d2) {
95 return d1.param_ != d2.param_;
96 }
97
98 private:
99 static constexpr uint64_t kP32 = static_cast<uint64_t>(1) << 32;
100
101 template <typename URBG>
102 static bool Generate(double p, URBG& g); // NOLINT(runtime/references)
103
104 param_type param_;
105 };
106
107 template <typename CharT, typename Traits>
108 std::basic_ostream<CharT, Traits>& operator<<(
109 std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
110 const bernoulli_distribution& x) {
111 auto saver = random_internal::make_ostream_state_saver(os);
112 os.precision(random_internal::stream_precision_helper<double>::kPrecision);
113 os << x.p();
114 return os;
115 }
116
117 template <typename CharT, typename Traits>
118 std::basic_istream<CharT, Traits>& operator>>(
119 std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
120 bernoulli_distribution& x) { // NOLINT(runtime/references)
121 auto saver = random_internal::make_istream_state_saver(is);
122 auto p = random_internal::read_floating_point<double>(is);
123 if (!is.fail()) {
124 x.param(bernoulli_distribution::param_type(p));
125 }
126 return is;
127 }
128
129 template <typename URBG>
Generate(double p,URBG & g)130 bool bernoulli_distribution::Generate(double p,
131 URBG& g) { // NOLINT(runtime/references)
132 random_internal::FastUniformBits<uint32_t> fast_u32;
133
134 while (true) {
135 // There are two aspects of the definition of `c` below that are worth
136 // commenting on. First, because `p` is in the range [0, 1], `c` is in the
137 // range [0, 2^32] which does not fit in a uint32_t and therefore requires
138 // 64 bits.
139 //
140 // Second, `c` is constructed by first casting explicitly to a signed
141 // integer and then converting implicitly to an unsigned integer of the same
142 // size. This is done because the hardware conversion instructions produce
143 // signed integers from double; if taken as a uint64_t the conversion would
144 // be wrong for doubles greater than 2^63 (not relevant in this use-case).
145 // If converted directly to an unsigned integer, the compiler would end up
146 // emitting code to handle such large values that are not relevant due to
147 // the known bounds on `c`. To avoid these extra instructions this
148 // implementation converts first to the signed type and then use the
149 // implicit conversion to unsigned (which is a no-op).
150 const uint64_t c = static_cast<int64_t>(p * kP32);
151 const uint32_t v = fast_u32(g);
152 // FAST PATH: this path fails with probability 1/2^32. Note that simply
153 // returning v <= c would approximate P very well (up to an absolute error
154 // of 1/2^32); the slow path (taken in that range of possible error, in the
155 // case of equality) eliminates the remaining error.
156 if (ABSL_PREDICT_TRUE(v != c)) return v < c;
157
158 // It is guaranteed that `q` is strictly less than 1, because if `q` were
159 // greater than or equal to 1, the same would be true for `p`. Certainly `p`
160 // cannot be greater than 1, and if `p == 1`, then the fast path would
161 // necessary have been taken already.
162 const double q = static_cast<double>(c) / kP32;
163
164 // The probability of acceptance on the fast path is `q` and so the
165 // probability of acceptance here should be `p - q`.
166 //
167 // Note that `q` is obtained from `p` via some shifts and conversions, the
168 // upshot of which is that `q` is simply `p` with some of the
169 // least-significant bits of its mantissa set to zero. This means that the
170 // difference `p - q` will not have any rounding errors. To see why, pretend
171 // that double has 10 bits of resolution and q is obtained from `p` in such
172 // a way that the 4 least-significant bits of its mantissa are set to zero.
173 // For example:
174 // p = 1.1100111011 * 2^-1
175 // q = 1.1100110000 * 2^-1
176 // p - q = 1.011 * 2^-8
177 // The difference `p - q` has exactly the nonzero mantissa bits that were
178 // "lost" in `q` producing a number which is certainly representable in a
179 // double.
180 const double left = p - q;
181
182 // By construction, the probability of being on this slow path is 1/2^32, so
183 // P(accept in slow path) = P(accept| in slow path) * P(slow path),
184 // which means the probability of acceptance here is `1 / (left * kP32)`:
185 const double here = left * kP32;
186
187 // The simplest way to compute the result of this trial is to repeat the
188 // whole algorithm with the new probability. This terminates because even
189 // given arbitrarily unfriendly "random" bits, each iteration either
190 // multiplies a tiny probability by 2^32 (if c == 0) or strips off some
191 // number of nonzero mantissa bits. That process is bounded.
192 if (here == 0) return false;
193 p = here;
194 }
195 }
196
197 ABSL_NAMESPACE_END
198 } // namespace absl
199
200 #endif // ABSL_RANDOM_BERNOULLI_DISTRIBUTION_H_
201