bernoulli_distribution.h 7.4 KB

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