abseil-cpp/absl/random/bernoulli_distribution.h
Go to the documentation of this file.
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 {
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
36  public:
37  using result_type = bool;
38 
39  class param_type {
40  public:
42 
43  explicit param_type(double p = 0.5) : prob_(p) {
44  assert(p >= 0.0 && p <= 1.0);
45  }
46 
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 
61 
62  explicit bernoulli_distribution(double p) : param_(p) {}
63 
65 
66  // no-op
67  void reset() {}
68 
69  template <typename URBG>
70  bool operator()(URBG& g) { // NOLINT(runtime/references)
71  return Generate(param_.p(), g);
72  }
73 
74  template <typename URBG>
75  bool operator()(URBG& g, // NOLINT(runtime/references)
76  const param_type& param) {
77  return Generate(param.p(), g);
78  }
79 
80  param_type param() const { return param_; }
81  void param(const param_type& param) { param_ = param; }
82 
83  double p() const { return param_.p(); }
84 
85  result_type(min)() const { return false; }
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 
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) {
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)
122  auto p = random_internal::read_floating_point<double>(is);
123  if (!is.fail()) {
125  }
126  return is;
127 }
128 
129 template <typename URBG>
131  URBG& g) { // NOLINT(runtime/references)
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 casting explicitly 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 convert to
149  // unsigned (which is a no-op).
150  const uint64_t c = static_cast<uint64_t>(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 
198 } // namespace absl
199 
200 #endif // ABSL_RANDOM_BERNOULLI_DISTRIBUTION_H_
absl::bernoulli_distribution::bernoulli_distribution
bernoulli_distribution()
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:60
bool
bool
Definition: setup_once.h:312
absl::bernoulli_distribution::operator==
friend bool operator==(const bernoulli_distribution &d1, const bernoulli_distribution &d2)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:88
absl::bernoulli_distribution::Generate
static bool Generate(double p, URBG &g)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:130
absl::bernoulli_distribution::param
param_type param() const
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:80
absl::bernoulli_distribution::max
result_type() max() const
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:86
absl::bernoulli_distribution::operator!=
friend bool operator!=(const bernoulli_distribution &d1, const bernoulli_distribution &d2)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:93
absl::random_internal::make_istream_state_saver
istream_state_saver< std::basic_istream< CharT, Traits > > make_istream_state_saver(std::basic_istream< CharT, Traits > &is, std::ios_base::fmtflags flags=std::ios_base::dec|std::ios_base::scientific|std::ios_base::skipws)
Definition: abseil-cpp/absl/random/internal/iostream_state_saver.h:149
absl::operator<<
ABSL_NAMESPACE_BEGIN std::ostream & operator<<(std::ostream &os, absl::LogSeverity s)
Definition: abseil-cpp/absl/base/log_severity.cc:24
absl::bernoulli_distribution::operator()
bool operator()(URBG &g, const param_type &param)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:75
absl::bernoulli_distribution::param
void param(const param_type &param)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:81
absl::bernoulli_distribution
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:35
absl::bernoulli_distribution::param_
param_type param_
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:104
absl::bernoulli_distribution::reset
void reset()
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:67
ABSL_NAMESPACE_END
#define ABSL_NAMESPACE_END
Definition: third_party/abseil-cpp/absl/base/config.h:171
absl::bernoulli_distribution::min
result_type() min() const
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:85
absl::bernoulli_distribution::param_type::prob_
double prob_
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:57
absl::bernoulli_distribution::param_type::p
double p() const
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:47
uint32_t
unsigned int uint32_t
Definition: stdint-msvc2008.h:80
ABSL_NAMESPACE_BEGIN
#define ABSL_NAMESPACE_BEGIN
Definition: third_party/abseil-cpp/absl/base/config.h:170
d2
static const fe d2
Definition: curve25519_tables.h:39
int64_t
signed __int64 int64_t
Definition: stdint-msvc2008.h:89
setup.v
v
Definition: third_party/bloaty/third_party/capstone/bindings/python/setup.py:42
uint64_t
unsigned __int64 uint64_t
Definition: stdint-msvc2008.h:90
absl::bernoulli_distribution::param_type::operator==
friend bool operator==(const param_type &p1, const param_type &p2)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:49
absl::bernoulli_distribution::param_type
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:39
absl::bernoulli_distribution::p
double p() const
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:83
x
int x
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3610
absl::bernoulli_distribution::result_type
bool result_type
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:37
absl::bernoulli_distribution::kP32
static constexpr uint64_t kP32
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:99
g
struct @717 g
absl::bernoulli_distribution::bernoulli_distribution
bernoulli_distribution(double p)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:62
absl::random_internal::stream_precision_helper
Definition: abseil-cpp/absl/random/internal/iostream_state_saver.h:107
ABSL_PREDICT_TRUE
#define ABSL_PREDICT_TRUE(x)
Definition: abseil-cpp/absl/base/optimization.h:181
absl::operator>>
constexpr uint128 operator>>(uint128 lhs, int amount)
Definition: abseil-cpp/absl/numeric/int128.h:917
absl::bernoulli_distribution::operator()
bool operator()(URBG &g)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:70
absl
Definition: abseil-cpp/absl/algorithm/algorithm.h:31
absl::bernoulli_distribution::param_type::operator!=
friend bool operator!=(const param_type &p1, const param_type &p2)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:52
absl::random_internal::make_ostream_state_saver
ostream_state_saver< std::basic_ostream< CharT, Traits > > make_ostream_state_saver(std::basic_ostream< CharT, Traits > &os, std::ios_base::fmtflags flags=std::ios_base::dec|std::ios_base::left|std::ios_base::scientific)
Definition: abseil-cpp/absl/random/internal/iostream_state_saver.h:82
absl::bernoulli_distribution::param_type::param_type
param_type(double p=0.5)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:43
absl::bernoulli_distribution::bernoulli_distribution
bernoulli_distribution(param_type p)
Definition: abseil-cpp/absl/random/bernoulli_distribution.h:64
absl::random_internal::FastUniformBits
Definition: abseil-cpp/absl/random/internal/fast_uniform_bits.h:89


grpc
Author(s):
autogenerated on Fri May 16 2025 02:57:46