poisson_distribution_test.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. #include "absl/random/poisson_distribution.h"
  15. #include <algorithm>
  16. #include <cstddef>
  17. #include <cstdint>
  18. #include <iterator>
  19. #include <random>
  20. #include <sstream>
  21. #include <string>
  22. #include <vector>
  23. #include "gmock/gmock.h"
  24. #include "gtest/gtest.h"
  25. #include "absl/base/internal/raw_logging.h"
  26. #include "absl/base/macros.h"
  27. #include "absl/container/flat_hash_map.h"
  28. #include "absl/random/internal/chi_square.h"
  29. #include "absl/random/internal/distribution_test_util.h"
  30. #include "absl/random/internal/pcg_engine.h"
  31. #include "absl/random/internal/sequence_urbg.h"
  32. #include "absl/random/random.h"
  33. #include "absl/strings/str_cat.h"
  34. #include "absl/strings/str_format.h"
  35. #include "absl/strings/str_replace.h"
  36. #include "absl/strings/strip.h"
  37. // Notes about generating poisson variates:
  38. //
  39. // It is unlikely that any implementation of std::poisson_distribution
  40. // will be stable over time and across library implementations. For instance
  41. // the three different poisson variate generators listed below all differ:
  42. //
  43. // https://github.com/ampl/gsl/tree/master/randist/poisson.c
  44. // * GSL uses a gamma + binomial + knuth method to compute poisson variates.
  45. //
  46. // https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/random.tcc
  47. // * GCC uses the Devroye rejection algorithm, based on
  48. // Devroye, L. Non-Uniform Random Variates Generation. Springer-Verlag,
  49. // New York, 1986, Ch. X, Sects. 3.3 & 3.4 (+ Errata!), ~p.511
  50. // http://www.nrbook.com/devroye/
  51. //
  52. // https://github.com/llvm-mirror/libcxx/blob/master/include/random
  53. // * CLANG uses a different rejection method, which appears to include a
  54. // normal-distribution approximation and an exponential distribution to
  55. // compute the threshold, including a similar factorial approximation to this
  56. // one, but it is unclear where the algorithm comes from, exactly.
  57. //
  58. namespace {
  59. using absl::random_internal::kChiSquared;
  60. // The PoissonDistributionInterfaceTest provides a basic test that
  61. // absl::poisson_distribution conforms to the interface and serialization
  62. // requirements imposed by [rand.req.dist] for the common integer types.
  63. template <typename IntType>
  64. class PoissonDistributionInterfaceTest : public ::testing::Test {};
  65. using IntTypes = ::testing::Types<int, int8_t, int16_t, int32_t, int64_t,
  66. uint8_t, uint16_t, uint32_t, uint64_t>;
  67. TYPED_TEST_CASE(PoissonDistributionInterfaceTest, IntTypes);
  68. TYPED_TEST(PoissonDistributionInterfaceTest, SerializeTest) {
  69. using param_type = typename absl::poisson_distribution<TypeParam>::param_type;
  70. const double kMax =
  71. std::min(1e10 /* assertion limit */,
  72. static_cast<double>(std::numeric_limits<TypeParam>::max()));
  73. const double kParams[] = {
  74. // Cases around 1.
  75. 1, //
  76. std::nextafter(1.0, 0.0), // 1 - epsilon
  77. std::nextafter(1.0, 2.0), // 1 + epsilon
  78. // Arbitrary values.
  79. 1e-8, 1e-4,
  80. 0.0000005, // ~7.2e-7
  81. 0.2, // ~0.2x
  82. 0.5, // 0.72
  83. 2, // ~2.8
  84. 20, // 3x ~9.6
  85. 100, 1e4, 1e8, 1.5e9, 1e20,
  86. // Boundary cases.
  87. std::numeric_limits<double>::max(),
  88. std::numeric_limits<double>::epsilon(),
  89. std::nextafter(std::numeric_limits<double>::min(),
  90. 1.0), // min + epsilon
  91. std::numeric_limits<double>::min(), // smallest normal
  92. std::numeric_limits<double>::denorm_min(), // smallest denorm
  93. std::numeric_limits<double>::min() / 2, // denorm
  94. std::nextafter(std::numeric_limits<double>::min(),
  95. 0.0), // denorm_max
  96. };
  97. constexpr int kCount = 1000;
  98. absl::InsecureBitGen gen;
  99. for (const double m : kParams) {
  100. const double mean = std::min(kMax, m);
  101. const param_type param(mean);
  102. // Validate parameters.
  103. absl::poisson_distribution<TypeParam> before(mean);
  104. EXPECT_EQ(before.mean(), param.mean());
  105. {
  106. absl::poisson_distribution<TypeParam> via_param(param);
  107. EXPECT_EQ(via_param, before);
  108. EXPECT_EQ(via_param.param(), before.param());
  109. }
  110. // Smoke test.
  111. auto sample_min = before.max();
  112. auto sample_max = before.min();
  113. for (int i = 0; i < kCount; i++) {
  114. auto sample = before(gen);
  115. EXPECT_GE(sample, before.min());
  116. EXPECT_LE(sample, before.max());
  117. if (sample > sample_max) sample_max = sample;
  118. if (sample < sample_min) sample_min = sample;
  119. }
  120. ABSL_INTERNAL_LOG(INFO, absl::StrCat("Range {", param.mean(), "}: ",
  121. +sample_min, ", ", +sample_max));
  122. // Validate stream serialization.
  123. std::stringstream ss;
  124. ss << before;
  125. absl::poisson_distribution<TypeParam> after(3.8);
  126. EXPECT_NE(before.mean(), after.mean());
  127. EXPECT_NE(before.param(), after.param());
  128. EXPECT_NE(before, after);
  129. ss >> after;
  130. EXPECT_EQ(before.mean(), after.mean()) //
  131. << ss.str() << " " //
  132. << (ss.good() ? "good " : "") //
  133. << (ss.bad() ? "bad " : "") //
  134. << (ss.eof() ? "eof " : "") //
  135. << (ss.fail() ? "fail " : "");
  136. }
  137. }
  138. // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda366j.htm
  139. class PoissonModel {
  140. public:
  141. explicit PoissonModel(double mean) : mean_(mean) {}
  142. double mean() const { return mean_; }
  143. double variance() const { return mean_; }
  144. double stddev() const { return std::sqrt(variance()); }
  145. double skew() const { return 1.0 / mean_; }
  146. double kurtosis() const { return 3.0 + 1.0 / mean_; }
  147. // InitCDF() initializes the CDF for the distribution parameters.
  148. void InitCDF();
  149. // The InverseCDF, or the Percent-point function returns x, P(x) < v.
  150. struct CDF {
  151. size_t index;
  152. double pmf;
  153. double cdf;
  154. };
  155. CDF InverseCDF(double p) {
  156. CDF target{0, 0, p};
  157. auto it = std::upper_bound(
  158. std::begin(cdf_), std::end(cdf_), target,
  159. [](const CDF& a, const CDF& b) { return a.cdf < b.cdf; });
  160. return *it;
  161. }
  162. void LogCDF() {
  163. ABSL_INTERNAL_LOG(INFO, absl::StrCat("CDF (mean = ", mean_, ")"));
  164. for (const auto c : cdf_) {
  165. ABSL_INTERNAL_LOG(INFO,
  166. absl::StrCat(c.index, ": pmf=", c.pmf, " cdf=", c.cdf));
  167. }
  168. }
  169. private:
  170. const double mean_;
  171. std::vector<CDF> cdf_;
  172. };
  173. // The goal is to compute an InverseCDF function, or percent point function for
  174. // the poisson distribution, and use that to partition our output into equal
  175. // range buckets. However there is no closed form solution for the inverse cdf
  176. // for poisson distributions (the closest is the incomplete gamma function).
  177. // Instead, `InitCDF` iteratively computes the PMF and the CDF. This enables
  178. // searching for the bucket points.
  179. void PoissonModel::InitCDF() {
  180. if (!cdf_.empty()) {
  181. // State already initialized.
  182. return;
  183. }
  184. ABSL_ASSERT(mean_ < 201.0);
  185. const size_t max_i = 50 * stddev() + mean();
  186. const double e_neg_mean = std::exp(-mean());
  187. ABSL_ASSERT(e_neg_mean > 0);
  188. double d = 1;
  189. double last_result = e_neg_mean;
  190. double cumulative = e_neg_mean;
  191. if (e_neg_mean > 1e-10) {
  192. cdf_.push_back({0, e_neg_mean, cumulative});
  193. }
  194. for (size_t i = 1; i < max_i; i++) {
  195. d *= (mean() / i);
  196. double result = e_neg_mean * d;
  197. cumulative += result;
  198. if (result < 1e-10 && result < last_result && cumulative > 0.999999) {
  199. break;
  200. }
  201. if (result > 1e-7) {
  202. cdf_.push_back({i, result, cumulative});
  203. }
  204. last_result = result;
  205. }
  206. ABSL_ASSERT(!cdf_.empty());
  207. }
  208. // PoissonDistributionZTest implements a z-test for the poisson distribution.
  209. struct ZParam {
  210. double mean;
  211. double p_fail; // Z-Test probability of failure.
  212. int trials; // Z-Test trials.
  213. size_t samples; // Z-Test samples.
  214. };
  215. class PoissonDistributionZTest : public testing::TestWithParam<ZParam>,
  216. public PoissonModel {
  217. public:
  218. PoissonDistributionZTest() : PoissonModel(GetParam().mean) {}
  219. // ZTestImpl provides a basic z-squared test of the mean vs. expected
  220. // mean for data generated by the poisson distribution.
  221. template <typename D>
  222. bool SingleZTest(const double p, const size_t samples);
  223. // We use a fixed bit generator for distribution accuracy tests. This allows
  224. // these tests to be deterministic, while still testing the qualify of the
  225. // implementation.
  226. absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
  227. };
  228. template <typename D>
  229. bool PoissonDistributionZTest::SingleZTest(const double p,
  230. const size_t samples) {
  231. D dis(mean());
  232. absl::flat_hash_map<int32_t, int> buckets;
  233. std::vector<double> data;
  234. data.reserve(samples);
  235. for (int j = 0; j < samples; j++) {
  236. const auto x = dis(rng_);
  237. buckets[x]++;
  238. data.push_back(x);
  239. }
  240. // The null-hypothesis is that the distribution is a poisson distribution with
  241. // the provided mean (not estimated from the data).
  242. const auto m = absl::random_internal::ComputeDistributionMoments(data);
  243. const double max_err = absl::random_internal::MaxErrorTolerance(p);
  244. const double z = absl::random_internal::ZScore(mean(), m);
  245. const bool pass = absl::random_internal::Near("z", z, 0.0, max_err);
  246. if (!pass) {
  247. ABSL_INTERNAL_LOG(
  248. INFO, absl::StrFormat("p=%f max_err=%f\n"
  249. " mean=%f vs. %f\n"
  250. " stddev=%f vs. %f\n"
  251. " skewness=%f vs. %f\n"
  252. " kurtosis=%f vs. %f\n"
  253. " z=%f",
  254. p, max_err, m.mean, mean(), std::sqrt(m.variance),
  255. stddev(), m.skewness, skew(), m.kurtosis,
  256. kurtosis(), z));
  257. }
  258. return pass;
  259. }
  260. TEST_P(PoissonDistributionZTest, AbslPoissonDistribution) {
  261. const auto& param = GetParam();
  262. const int expected_failures =
  263. std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail)));
  264. const double p = absl::random_internal::RequiredSuccessProbability(
  265. param.p_fail, param.trials);
  266. int failures = 0;
  267. for (int i = 0; i < param.trials; i++) {
  268. failures +=
  269. SingleZTest<absl::poisson_distribution<int32_t>>(p, param.samples) ? 0
  270. : 1;
  271. }
  272. EXPECT_LE(failures, expected_failures);
  273. }
  274. std::vector<ZParam> GetZParams() {
  275. // These values have been adjusted from the "exact" computed values to reduce
  276. // failure rates.
  277. //
  278. // It turns out that the actual values are not as close to the expected values
  279. // as would be ideal.
  280. return std::vector<ZParam>({
  281. // Knuth method.
  282. ZParam{0.5, 0.01, 100, 1000},
  283. ZParam{1.0, 0.01, 100, 1000},
  284. ZParam{10.0, 0.01, 100, 5000},
  285. // Split-knuth method.
  286. ZParam{20.0, 0.01, 100, 10000},
  287. ZParam{50.0, 0.01, 100, 10000},
  288. // Ratio of gaussians method.
  289. ZParam{51.0, 0.01, 100, 10000},
  290. ZParam{200.0, 0.05, 10, 100000},
  291. ZParam{100000.0, 0.05, 10, 1000000},
  292. });
  293. }
  294. std::string ZParamName(const ::testing::TestParamInfo<ZParam>& info) {
  295. const auto& p = info.param;
  296. std::string name = absl::StrCat("mean_", absl::SixDigits(p.mean));
  297. return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
  298. }
  299. INSTANTIATE_TEST_SUITE_P(All, PoissonDistributionZTest,
  300. ::testing::ValuesIn(GetZParams()), ZParamName);
  301. // The PoissonDistributionChiSquaredTest class provides a basic test framework
  302. // for variates generated by a conforming poisson_distribution.
  303. class PoissonDistributionChiSquaredTest : public testing::TestWithParam<double>,
  304. public PoissonModel {
  305. public:
  306. PoissonDistributionChiSquaredTest() : PoissonModel(GetParam()) {}
  307. // The ChiSquaredTestImpl provides a chi-squared goodness of fit test for data
  308. // generated by the poisson distribution.
  309. template <typename D>
  310. double ChiSquaredTestImpl();
  311. private:
  312. void InitChiSquaredTest(const double buckets);
  313. std::vector<size_t> cutoffs_;
  314. std::vector<double> expected_;
  315. // We use a fixed bit generator for distribution accuracy tests. This allows
  316. // these tests to be deterministic, while still testing the qualify of the
  317. // implementation.
  318. absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
  319. };
  320. void PoissonDistributionChiSquaredTest::InitChiSquaredTest(
  321. const double buckets) {
  322. if (!cutoffs_.empty() && !expected_.empty()) {
  323. return;
  324. }
  325. InitCDF();
  326. // The code below finds cuttoffs that yield approximately equally-sized
  327. // buckets to the extent that it is possible. However for poisson
  328. // distributions this is particularly challenging for small mean parameters.
  329. // Track the expected proportion of items in each bucket.
  330. double last_cdf = 0;
  331. const double inc = 1.0 / buckets;
  332. for (double p = inc; p <= 1.0; p += inc) {
  333. auto result = InverseCDF(p);
  334. if (!cutoffs_.empty() && cutoffs_.back() == result.index) {
  335. continue;
  336. }
  337. double d = result.cdf - last_cdf;
  338. cutoffs_.push_back(result.index);
  339. expected_.push_back(d);
  340. last_cdf = result.cdf;
  341. }
  342. cutoffs_.push_back(std::numeric_limits<size_t>::max());
  343. expected_.push_back(std::max(0.0, 1.0 - last_cdf));
  344. }
  345. template <typename D>
  346. double PoissonDistributionChiSquaredTest::ChiSquaredTestImpl() {
  347. const int kSamples = 2000;
  348. const int kBuckets = 50;
  349. // The poisson CDF fails for large mean values, since e^-mean exceeds the
  350. // machine precision. For these cases, using a normal approximation would be
  351. // appropriate.
  352. ABSL_ASSERT(mean() <= 200);
  353. InitChiSquaredTest(kBuckets);
  354. D dis(mean());
  355. std::vector<int32_t> counts(cutoffs_.size(), 0);
  356. for (int j = 0; j < kSamples; j++) {
  357. const size_t x = dis(rng_);
  358. auto it = std::lower_bound(std::begin(cutoffs_), std::end(cutoffs_), x);
  359. counts[std::distance(cutoffs_.begin(), it)]++;
  360. }
  361. // Normalize the counts.
  362. std::vector<int32_t> e(expected_.size(), 0);
  363. for (int i = 0; i < e.size(); i++) {
  364. e[i] = kSamples * expected_[i];
  365. }
  366. // The null-hypothesis is that the distribution is a poisson distribution with
  367. // the provided mean (not estimated from the data).
  368. const int dof = static_cast<int>(counts.size()) - 1;
  369. // The threshold for logging is 1-in-50.
  370. const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
  371. const double chi_square = absl::random_internal::ChiSquare(
  372. std::begin(counts), std::end(counts), std::begin(e), std::end(e));
  373. const double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
  374. // Log if the chi_squared value is above the threshold.
  375. if (chi_square > threshold) {
  376. LogCDF();
  377. ABSL_INTERNAL_LOG(INFO, absl::StrCat("VALUES buckets=", counts.size(),
  378. " samples=", kSamples));
  379. for (size_t i = 0; i < counts.size(); i++) {
  380. ABSL_INTERNAL_LOG(
  381. INFO, absl::StrCat(cutoffs_[i], ": ", counts[i], " vs. E=", e[i]));
  382. }
  383. ABSL_INTERNAL_LOG(
  384. INFO,
  385. absl::StrCat(kChiSquared, "(data, dof=", dof, ") = ", chi_square, " (",
  386. p, ")\n", " vs.\n", kChiSquared, " @ 0.98 = ", threshold));
  387. }
  388. return p;
  389. }
  390. TEST_P(PoissonDistributionChiSquaredTest, AbslPoissonDistribution) {
  391. const int kTrials = 20;
  392. // Large values are not yet supported -- this requires estimating the cdf
  393. // using the normal distribution instead of the poisson in this case.
  394. ASSERT_LE(mean(), 200.0);
  395. if (mean() > 200.0) {
  396. return;
  397. }
  398. int failures = 0;
  399. for (int i = 0; i < kTrials; i++) {
  400. double p_value = ChiSquaredTestImpl<absl::poisson_distribution<int32_t>>();
  401. if (p_value < 0.005) {
  402. failures++;
  403. }
  404. }
  405. // There is a 0.10% chance of producing at least one failure, so raise the
  406. // failure threshold high enough to allow for a flake rate < 10,000.
  407. EXPECT_LE(failures, 4);
  408. }
  409. INSTANTIATE_TEST_SUITE_P(All, PoissonDistributionChiSquaredTest,
  410. ::testing::Values(0.5, 1.0, 2.0, 10.0, 50.0, 51.0,
  411. 200.0));
  412. // NOTE: absl::poisson_distribution is not guaranteed to be stable.
  413. TEST(PoissonDistributionTest, StabilityTest) {
  414. using testing::ElementsAre;
  415. // absl::poisson_distribution stability relies on stability of
  416. // std::exp, std::log, std::sqrt, std::ceil, std::floor, and
  417. // absl::FastUniformBits, absl::StirlingLogFactorial, absl::RandU64ToDouble.
  418. absl::random_internal::sequence_urbg urbg({
  419. 0x035b0dc7e0a18acfull, 0x06cebe0d2653682eull, 0x0061e9b23861596bull,
  420. 0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
  421. 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
  422. 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
  423. 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull,
  424. 0x4864f22c059bf29eull, 0x247856d8b862665cull, 0xe46e86e9a1337e10ull,
  425. 0xd8c8541f3519b133ull, 0xe75b5162c567b9e4ull, 0xf732e5ded7009c5bull,
  426. 0xb170b98353121eacull, 0x1ec2e8986d2362caull, 0x814c8e35fe9a961aull,
  427. 0x0c3cd59c9b638a02ull, 0xcb3bb6478a07715cull, 0x1224e62c978bbc7full,
  428. 0x671ef2cb04e81f6eull, 0x3c1cbd811eaf1808ull, 0x1bbc23cfa8fac721ull,
  429. 0xa4c2cda65e596a51ull, 0xb77216fad37adf91ull, 0x836d794457c08849ull,
  430. 0xe083df03475f49d7ull, 0xbc9feb512e6b0d6cull, 0xb12d74fdd718c8c5ull,
  431. 0x12ff09653bfbe4caull, 0x8dd03a105bc4ee7eull, 0x5738341045ba0d85ull,
  432. 0xf3fd722dc65ad09eull, 0xfa14fd21ea2a5705ull, 0xffe6ea4d6edb0c73ull,
  433. 0xD07E9EFE2BF11FB4ull, 0x95DBDA4DAE909198ull, 0xEAAD8E716B93D5A0ull,
  434. 0xD08ED1D0AFC725E0ull, 0x8E3C5B2F8E7594B7ull, 0x8FF6E2FBF2122B64ull,
  435. 0x8888B812900DF01Cull, 0x4FAD5EA0688FC31Cull, 0xD1CFF191B3A8C1ADull,
  436. 0x2F2F2218BE0E1777ull, 0xEA752DFE8B021FA1ull, 0xE5A0CC0FB56F74E8ull,
  437. 0x18ACF3D6CE89E299ull, 0xB4A84FE0FD13E0B7ull, 0x7CC43B81D2ADA8D9ull,
  438. 0x165FA26680957705ull, 0x93CC7314211A1477ull, 0xE6AD206577B5FA86ull,
  439. 0xC75442F5FB9D35CFull, 0xEBCDAF0C7B3E89A0ull, 0xD6411BD3AE1E7E49ull,
  440. 0x00250E2D2071B35Eull, 0x226800BB57B8E0AFull, 0x2464369BF009B91Eull,
  441. 0x5563911D59DFA6AAull, 0x78C14389D95A537Full, 0x207D5BA202E5B9C5ull,
  442. 0x832603766295CFA9ull, 0x11C819684E734A41ull, 0xB3472DCA7B14A94Aull,
  443. });
  444. std::vector<int> output(10);
  445. // Method 1.
  446. {
  447. absl::poisson_distribution<int> dist(5);
  448. std::generate(std::begin(output), std::end(output),
  449. [&] { return dist(urbg); });
  450. }
  451. EXPECT_THAT(output, // mean = 4.2
  452. ElementsAre(1, 0, 0, 4, 2, 10, 3, 3, 7, 12));
  453. // Method 2.
  454. {
  455. urbg.reset();
  456. absl::poisson_distribution<int> dist(25);
  457. std::generate(std::begin(output), std::end(output),
  458. [&] { return dist(urbg); });
  459. }
  460. EXPECT_THAT(output, // mean = 19.8
  461. ElementsAre(9, 35, 18, 10, 35, 18, 10, 35, 18, 10));
  462. // Method 3.
  463. {
  464. urbg.reset();
  465. absl::poisson_distribution<int> dist(121);
  466. std::generate(std::begin(output), std::end(output),
  467. [&] { return dist(urbg); });
  468. }
  469. EXPECT_THAT(output, // mean = 124.1
  470. ElementsAre(161, 122, 129, 124, 112, 112, 117, 120, 130, 114));
  471. }
  472. TEST(PoissonDistributionTest, AlgorithmExpectedValue_1) {
  473. // This tests small values of the Knuth method.
  474. // The underlying uniform distribution will generate exactly 0.5.
  475. absl::random_internal::sequence_urbg urbg({0x8000000000000001ull});
  476. absl::poisson_distribution<int> dist(5);
  477. EXPECT_EQ(7, dist(urbg));
  478. }
  479. TEST(PoissonDistributionTest, AlgorithmExpectedValue_2) {
  480. // This tests larger values of the Knuth method.
  481. // The underlying uniform distribution will generate exactly 0.5.
  482. absl::random_internal::sequence_urbg urbg({0x8000000000000001ull});
  483. absl::poisson_distribution<int> dist(25);
  484. EXPECT_EQ(36, dist(urbg));
  485. }
  486. TEST(PoissonDistributionTest, AlgorithmExpectedValue_3) {
  487. // This variant uses the ratio of uniforms method.
  488. absl::random_internal::sequence_urbg urbg(
  489. {0x7fffffffffffffffull, 0x8000000000000000ull});
  490. absl::poisson_distribution<int> dist(121);
  491. EXPECT_EQ(121, dist(urbg));
  492. }
  493. } // namespace