poisson_distribution.h 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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_POISSON_DISTRIBUTION_H_
  15. #define ABSL_RANDOM_POISSON_DISTRIBUTION_H_
  16. #include <cassert>
  17. #include <cmath>
  18. #include <istream>
  19. #include <limits>
  20. #include <ostream>
  21. #include <type_traits>
  22. #include "absl/random/internal/fast_uniform_bits.h"
  23. #include "absl/random/internal/fastmath.h"
  24. #include "absl/random/internal/generate_real.h"
  25. #include "absl/random/internal/iostream_state_saver.h"
  26. namespace absl {
  27. ABSL_NAMESPACE_BEGIN
  28. // absl::poisson_distribution:
  29. // Generates discrete variates conforming to a Poisson distribution.
  30. // p(n) = (mean^n / n!) exp(-mean)
  31. //
  32. // Depending on the parameter, the distribution selects one of the following
  33. // algorithms:
  34. // * The standard algorithm, attributed to Knuth, extended using a split method
  35. // for larger values
  36. // * The "Ratio of Uniforms as a convenient method for sampling from classical
  37. // discrete distributions", Stadlober, 1989.
  38. // http://www.sciencedirect.com/science/article/pii/0377042790903495
  39. //
  40. // NOTE: param_type.mean() is a double, which permits values larger than
  41. // poisson_distribution<IntType>::max(), however this should be avoided and
  42. // the distribution results are limited to the max() value.
  43. //
  44. // The goals of this implementation are to provide good performance while still
  45. // beig thread-safe: This limits the implementation to not using lgamma provided
  46. // by <math.h>.
  47. //
  48. template <typename IntType = int>
  49. class poisson_distribution {
  50. public:
  51. using result_type = IntType;
  52. class param_type {
  53. public:
  54. using distribution_type = poisson_distribution;
  55. explicit param_type(double mean = 1.0);
  56. double mean() const { return mean_; }
  57. friend bool operator==(const param_type& a, const param_type& b) {
  58. return a.mean_ == b.mean_;
  59. }
  60. friend bool operator!=(const param_type& a, const param_type& b) {
  61. return !(a == b);
  62. }
  63. private:
  64. friend class poisson_distribution;
  65. double mean_;
  66. double emu_; // e ^ -mean_
  67. double lmu_; // ln(mean_)
  68. double s_;
  69. double log_k_;
  70. int split_;
  71. static_assert(std::is_integral<IntType>::value,
  72. "Class-template absl::poisson_distribution<> must be "
  73. "parameterized using an integral type.");
  74. };
  75. poisson_distribution() : poisson_distribution(1.0) {}
  76. explicit poisson_distribution(double mean) : param_(mean) {}
  77. explicit poisson_distribution(const param_type& p) : param_(p) {}
  78. void reset() {}
  79. // generating functions
  80. template <typename URBG>
  81. result_type operator()(URBG& g) { // NOLINT(runtime/references)
  82. return (*this)(g, param_);
  83. }
  84. template <typename URBG>
  85. result_type operator()(URBG& g, // NOLINT(runtime/references)
  86. const param_type& p);
  87. param_type param() const { return param_; }
  88. void param(const param_type& p) { param_ = p; }
  89. result_type(min)() const { return 0; }
  90. result_type(max)() const { return (std::numeric_limits<result_type>::max)(); }
  91. double mean() const { return param_.mean(); }
  92. friend bool operator==(const poisson_distribution& a,
  93. const poisson_distribution& b) {
  94. return a.param_ == b.param_;
  95. }
  96. friend bool operator!=(const poisson_distribution& a,
  97. const poisson_distribution& b) {
  98. return a.param_ != b.param_;
  99. }
  100. private:
  101. param_type param_;
  102. random_internal::FastUniformBits<uint64_t> fast_u64_;
  103. };
  104. // -----------------------------------------------------------------------------
  105. // Implementation details follow
  106. // -----------------------------------------------------------------------------
  107. template <typename IntType>
  108. poisson_distribution<IntType>::param_type::param_type(double mean)
  109. : mean_(mean), split_(0) {
  110. assert(mean >= 0);
  111. assert(mean <= (std::numeric_limits<result_type>::max)());
  112. // As a defensive measure, avoid large values of the mean. The rejection
  113. // algorithm used does not support very large values well. It my be worth
  114. // changing algorithms to better deal with these cases.
  115. assert(mean <= 1e10);
  116. if (mean_ < 10) {
  117. // For small lambda, use the knuth method.
  118. split_ = 1;
  119. emu_ = std::exp(-mean_);
  120. } else if (mean_ <= 50) {
  121. // Use split-knuth method.
  122. split_ = 1 + static_cast<int>(mean_ / 10.0);
  123. emu_ = std::exp(-mean_ / static_cast<double>(split_));
  124. } else {
  125. // Use ratio of uniforms method.
  126. constexpr double k2E = 0.7357588823428846;
  127. constexpr double kSA = 0.4494580810294493;
  128. lmu_ = std::log(mean_);
  129. double a = mean_ + 0.5;
  130. s_ = kSA + std::sqrt(k2E * a);
  131. const double mode = std::ceil(mean_) - 1;
  132. log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode);
  133. }
  134. }
  135. template <typename IntType>
  136. template <typename URBG>
  137. typename poisson_distribution<IntType>::result_type
  138. poisson_distribution<IntType>::operator()(
  139. URBG& g, // NOLINT(runtime/references)
  140. const param_type& p) {
  141. using random_internal::GeneratePositiveTag;
  142. using random_internal::GenerateRealFromBits;
  143. using random_internal::GenerateSignedTag;
  144. if (p.split_ != 0) {
  145. // Use Knuth's algorithm with range splitting to avoid floating-point
  146. // errors. Knuth's algorithm is: Ui is a sequence of uniform variates on
  147. // (0,1); return the number of variates required for product(Ui) <
  148. // exp(-lambda).
  149. //
  150. // The expected number of variates required for Knuth's method can be
  151. // computed as follows:
  152. // The expected value of U is 0.5, so solving for 0.5^n < exp(-lambda) gives
  153. // the expected number of uniform variates
  154. // required for a given lambda, which is:
  155. // lambda = [2, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17]
  156. // n = [3, 8, 13, 15, 16, 18, 19, 21, 22, 24, 25]
  157. //
  158. result_type n = 0;
  159. for (int split = p.split_; split > 0; --split) {
  160. double r = 1.0;
  161. do {
  162. r *= GenerateRealFromBits<double, GeneratePositiveTag, true>(
  163. fast_u64_(g)); // U(-1, 0)
  164. ++n;
  165. } while (r > p.emu_);
  166. --n;
  167. }
  168. return n;
  169. }
  170. // Use ratio of uniforms method.
  171. //
  172. // Let u ~ Uniform(0, 1), v ~ Uniform(-1, 1),
  173. // a = lambda + 1/2,
  174. // s = 1.5 - sqrt(3/e) + sqrt(2(lambda + 1/2)/e),
  175. // x = s * v/u + a.
  176. // P(floor(x) = k | u^2 < f(floor(x))/k), where
  177. // f(m) = lambda^m exp(-lambda)/ m!, for 0 <= m, and f(m) = 0 otherwise,
  178. // and k = max(f).
  179. const double a = p.mean_ + 0.5;
  180. for (;;) {
  181. const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>(
  182. fast_u64_(g)); // U(0, 1)
  183. const double v = GenerateRealFromBits<double, GenerateSignedTag, false>(
  184. fast_u64_(g)); // U(-1, 1)
  185. const double x = std::floor(p.s_ * v / u + a);
  186. if (x < 0) continue; // f(negative) = 0
  187. const double rhs = x * p.lmu_;
  188. // clang-format off
  189. double s = (x <= 1.0) ? 0.0
  190. : (x == 2.0) ? 0.693147180559945
  191. : absl::random_internal::StirlingLogFactorial(x);
  192. // clang-format on
  193. const double lhs = 2.0 * std::log(u) + p.log_k_ + s;
  194. if (lhs < rhs) {
  195. return x > (max)() ? (max)()
  196. : static_cast<result_type>(x); // f(x)/k >= u^2
  197. }
  198. }
  199. }
  200. template <typename CharT, typename Traits, typename IntType>
  201. std::basic_ostream<CharT, Traits>& operator<<(
  202. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  203. const poisson_distribution<IntType>& x) {
  204. auto saver = random_internal::make_ostream_state_saver(os);
  205. os.precision(random_internal::stream_precision_helper<double>::kPrecision);
  206. os << x.mean();
  207. return os;
  208. }
  209. template <typename CharT, typename Traits, typename IntType>
  210. std::basic_istream<CharT, Traits>& operator>>(
  211. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  212. poisson_distribution<IntType>& x) { // NOLINT(runtime/references)
  213. using param_type = typename poisson_distribution<IntType>::param_type;
  214. auto saver = random_internal::make_istream_state_saver(is);
  215. double mean = random_internal::read_floating_point<double>(is);
  216. if (!is.fail()) {
  217. x.param(param_type(mean));
  218. }
  219. return is;
  220. }
  221. ABSL_NAMESPACE_END
  222. } // namespace absl
  223. #endif // ABSL_RANDOM_POISSON_DISTRIBUTION_H_