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.

poisson_distribution.h 11 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. {
  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. // beig thread-safe: This limits the implementation to not using lgamma provided
  48. // by <math.h>.
  49. //
  50. template<typename IntType = int>
  51. class poisson_distribution
  52. {
  53. public:
  54. using result_type = IntType;
  55. class param_type
  56. {
  57. public:
  58. using distribution_type = poisson_distribution;
  59. explicit param_type(double mean = 1.0);
  60. double mean() const
  61. {
  62. return mean_;
  63. }
  64. friend bool operator==(const param_type& a, const param_type& b)
  65. {
  66. return a.mean_ == b.mean_;
  67. }
  68. friend bool operator!=(const param_type& a, const param_type& b)
  69. {
  70. return !(a == b);
  71. }
  72. private:
  73. friend class poisson_distribution;
  74. double mean_;
  75. double emu_; // e ^ -mean_
  76. double lmu_; // ln(mean_)
  77. double s_;
  78. double log_k_;
  79. int split_;
  80. static_assert(random_internal::IsIntegral<IntType>::value, "Class-template absl::poisson_distribution<> must be "
  81. "parameterized using an integral type.");
  82. };
  83. poisson_distribution() :
  84. poisson_distribution(1.0)
  85. {
  86. }
  87. explicit poisson_distribution(double mean) :
  88. param_(mean)
  89. {
  90. }
  91. explicit poisson_distribution(const param_type& p) :
  92. param_(p)
  93. {
  94. }
  95. void reset()
  96. {
  97. }
  98. // generating functions
  99. template<typename URBG>
  100. result_type operator()(URBG& g)
  101. { // NOLINT(runtime/references)
  102. return (*this)(g, param_);
  103. }
  104. template<typename URBG>
  105. result_type operator()(URBG& g, // NOLINT(runtime/references)
  106. const param_type& p);
  107. param_type param() const
  108. {
  109. return param_;
  110. }
  111. void param(const param_type& p)
  112. {
  113. param_ = p;
  114. }
  115. result_type(min)() const
  116. {
  117. return 0;
  118. }
  119. result_type(max)() const
  120. {
  121. return (std::numeric_limits<result_type>::max)();
  122. }
  123. double mean() const
  124. {
  125. return param_.mean();
  126. }
  127. friend bool operator==(const poisson_distribution& a, const poisson_distribution& b)
  128. {
  129. return a.param_ == b.param_;
  130. }
  131. friend bool operator!=(const poisson_distribution& a, const poisson_distribution& b)
  132. {
  133. return a.param_ != b.param_;
  134. }
  135. private:
  136. param_type param_;
  137. random_internal::FastUniformBits<uint64_t> fast_u64_;
  138. };
  139. // -----------------------------------------------------------------------------
  140. // Implementation details follow
  141. // -----------------------------------------------------------------------------
  142. template<typename IntType>
  143. poisson_distribution<IntType>::param_type::param_type(double mean) :
  144. mean_(mean),
  145. split_(0)
  146. {
  147. assert(mean >= 0);
  148. assert(mean <= static_cast<double>((std::numeric_limits<result_type>::max)()));
  149. // As a defensive measure, avoid large values of the mean. The rejection
  150. // algorithm used does not support very large values well. It my be worth
  151. // changing algorithms to better deal with these cases.
  152. assert(mean <= 1e10);
  153. if (mean_ < 10)
  154. {
  155. // For small lambda, use the knuth method.
  156. split_ = 1;
  157. emu_ = std::exp(-mean_);
  158. }
  159. else if (mean_ <= 50)
  160. {
  161. // Use split-knuth method.
  162. split_ = 1 + static_cast<int>(mean_ / 10.0);
  163. emu_ = std::exp(-mean_ / static_cast<double>(split_));
  164. }
  165. else
  166. {
  167. // Use ratio of uniforms method.
  168. constexpr double k2E = 0.7357588823428846;
  169. constexpr double kSA = 0.4494580810294493;
  170. lmu_ = std::log(mean_);
  171. double a = mean_ + 0.5;
  172. s_ = kSA + std::sqrt(k2E * a);
  173. const double mode = std::ceil(mean_) - 1;
  174. log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode);
  175. }
  176. }
  177. template<typename IntType>
  178. template<typename URBG>
  179. typename poisson_distribution<IntType>::result_type
  180. poisson_distribution<IntType>::operator()(
  181. URBG& g, // NOLINT(runtime/references)
  182. const param_type& p
  183. )
  184. {
  185. using random_internal::GeneratePositiveTag;
  186. using random_internal::GenerateRealFromBits;
  187. using random_internal::GenerateSignedTag;
  188. if (p.split_ != 0)
  189. {
  190. // Use Knuth's algorithm with range splitting to avoid floating-point
  191. // errors. Knuth's algorithm is: Ui is a sequence of uniform variates on
  192. // (0,1); return the number of variates required for product(Ui) <
  193. // exp(-lambda).
  194. //
  195. // The expected number of variates required for Knuth's method can be
  196. // computed as follows:
  197. // The expected value of U is 0.5, so solving for 0.5^n < exp(-lambda) gives
  198. // the expected number of uniform variates
  199. // required for a given lambda, which is:
  200. // lambda = [2, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17]
  201. // n = [3, 8, 13, 15, 16, 18, 19, 21, 22, 24, 25]
  202. //
  203. result_type n = 0;
  204. for (int split = p.split_; split > 0; --split)
  205. {
  206. double r = 1.0;
  207. do
  208. {
  209. r *= GenerateRealFromBits<double, GeneratePositiveTag, true>(
  210. fast_u64_(g)
  211. ); // U(-1, 0)
  212. ++n;
  213. } while (r > p.emu_);
  214. --n;
  215. }
  216. return n;
  217. }
  218. // Use ratio of uniforms method.
  219. //
  220. // Let u ~ Uniform(0, 1), v ~ Uniform(-1, 1),
  221. // a = lambda + 1/2,
  222. // s = 1.5 - sqrt(3/e) + sqrt(2(lambda + 1/2)/e),
  223. // x = s * v/u + a.
  224. // P(floor(x) = k | u^2 < f(floor(x))/k), where
  225. // f(m) = lambda^m exp(-lambda)/ m!, for 0 <= m, and f(m) = 0 otherwise,
  226. // and k = max(f).
  227. const double a = p.mean_ + 0.5;
  228. for (;;)
  229. {
  230. const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>(
  231. fast_u64_(g)
  232. ); // U(0, 1)
  233. const double v = GenerateRealFromBits<double, GenerateSignedTag, false>(
  234. fast_u64_(g)
  235. ); // U(-1, 1)
  236. const double x = std::floor(p.s_ * v / u + a);
  237. if (x < 0)
  238. continue; // f(negative) = 0
  239. const double rhs = x * p.lmu_;
  240. // clang-format off
  241. double s = (x <= 1.0) ? 0.0
  242. : (x == 2.0) ? 0.693147180559945
  243. : absl::random_internal::StirlingLogFactorial(x);
  244. // clang-format on
  245. const double lhs = 2.0 * std::log(u) + p.log_k_ + s;
  246. if (lhs < rhs)
  247. {
  248. return x > static_cast<double>((max)()) ? (max)() : static_cast<result_type>(x); // f(x)/k >= u^2
  249. }
  250. }
  251. }
  252. template<typename CharT, typename Traits, typename IntType>
  253. std::basic_ostream<CharT, Traits>& operator<<(
  254. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  255. const poisson_distribution<IntType>& x
  256. )
  257. {
  258. auto saver = random_internal::make_ostream_state_saver(os);
  259. os.precision(random_internal::stream_precision_helper<double>::kPrecision);
  260. os << x.mean();
  261. return os;
  262. }
  263. template<typename CharT, typename Traits, typename IntType>
  264. std::basic_istream<CharT, Traits>& operator>>(
  265. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  266. poisson_distribution<IntType>& x
  267. )
  268. { // NOLINT(runtime/references)
  269. using param_type = typename poisson_distribution<IntType>::param_type;
  270. auto saver = random_internal::make_istream_state_saver(is);
  271. double mean = random_internal::read_floating_point<double>(is);
  272. if (!is.fail())
  273. {
  274. x.param(param_type(mean));
  275. }
  276. return is;
  277. }
  278. ABSL_NAMESPACE_END
  279. } // namespace absl
  280. #endif // ABSL_RANDOM_POISSON_DISTRIBUTION_H_