poisson_distribution.h 8.7 KB

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