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