poisson_distribution.h 8.7 KB

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