You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

bernoulli_distribution.h 8.9 kB

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