Fix overflow, tiny-mean underflow, and cancellation in poisson_distribution. Extreme means and narrow result types previously broke `absl::poisson_distribution`: * In Knuth's product sampler, incrementing the count before testing `exp(-mean)` could overflow narrow signed result types or wrap narrow unsigned counts instead of clamping at `max()`. * For `0 < mean < 1.665e-16`, `exp(-mean)` rounded to `>= 1 - 2^-53` (matching the maximum `U[0, 1)` draw), causing the distribution to return `0` identically instead of sampling rare events with probability `mean`. * At large means, catastrophic cancellation in log-probability differences and `double` proposal arithmetic degraded accuracy above `mean ~ 1e8` (allowing the supported mean bound to increase from `1e10` to `1e15` once stabilized), and clamping near 64/128-bit `max()` risked float-to-int overflow UB. Output sequences change; `absl::poisson_distribution` does not guarantee cross-release stability. PiperOrigin-RevId: 1022528503
diff --git a/CMake/AbseilDll.cmake b/CMake/AbseilDll.cmake index dddb1a1..fbd2f8a 100644 --- a/CMake/AbseilDll.cmake +++ b/CMake/AbseilDll.cmake
@@ -270,6 +270,7 @@ "random/internal/uniform_helper.h" "random/internal/wide_multiply.h" "random/log_uniform_int_distribution.h" + "random/poisson_distribution.cc" "random/poisson_distribution.h" "random/random.h" "random/seed_gen_exception.cc"
diff --git a/absl/random/BUILD.bazel b/absl/random/BUILD.bazel index e34ba03..22a217c 100644 --- a/absl/random/BUILD.bazel +++ b/absl/random/BUILD.bazel
@@ -58,6 +58,7 @@ srcs = [ "discrete_distribution.cc", "gaussian_distribution.cc", + "poisson_distribution.cc", ], hdrs = [ "bernoulli_distribution.h", @@ -340,6 +341,7 @@ "//absl/base:core_headers", "//absl/container:flat_hash_map", "//absl/log", + "//absl/numeric:int128", "//absl/random/internal:distribution_test_util", "//absl/random/internal:pcg_engine", "//absl/random/internal:sequence_urbg",
diff --git a/absl/random/CMakeLists.txt b/absl/random/CMakeLists.txt index 224a477..e9b39e6 100644 --- a/absl/random/CMakeLists.txt +++ b/absl/random/CMakeLists.txt
@@ -186,6 +186,7 @@ SRCS "discrete_distribution.cc" "gaussian_distribution.cc" + "poisson_distribution.cc" HDRS "bernoulli_distribution.h" "beta_distribution.h" @@ -394,6 +395,7 @@ DEPS absl::core_headers absl::flat_hash_map + absl::int128 absl::log absl::random_distributions absl::random_internal_distribution_test_util
diff --git a/absl/random/internal/fastmath.h b/absl/random/internal/fastmath.h index 8f4f356..d6170e8 100644 --- a/absl/random/internal/fastmath.h +++ b/absl/random/internal/fastmath.h
@@ -51,6 +51,18 @@ (1.0 / 360.0) * ninv * ninv * ninv; } +// Returns the Stirling asymptotic remainder: +// ln(n!) - ((n + 0.5) * ln(n) - n + 0.5 * ln(2*pi)) +// For n >= 20, the 4-term series is accurate to < 2e-15. +inline double StirlingLogFactorialRemainder(double n) { + assert(n >= 1); + const double inv = 1.0 / n; + const double inv2 = inv * inv; + return inv * ((1.0 / 12.0) - + inv2 * ((1.0 / 360.0) - + inv2 * ((1.0 / 1260.0) - inv2 * (1.0 / 1680.0)))); +} + } // namespace random_internal ABSL_NAMESPACE_END } // namespace absl
diff --git a/absl/random/internal/fastmath_test.cc b/absl/random/internal/fastmath_test.cc index 563bb80..e046297 100644 --- a/absl/random/internal/fastmath_test.cc +++ b/absl/random/internal/fastmath_test.cc
@@ -97,4 +97,56 @@ } } +TEST(FastMathTest, StirlingLogFactorialRemainderMatchesReferenceValues) { + using absl::random_internal::StirlingLogFactorialRemainder; + + // High-precision values of R(n) = ln(n!) - ((n + 0.5) * ln(n) - n + 0.5 * + // ln(2 * pi)) within the < 2e-15 bound for n >= 20. + EXPECT_NEAR(StirlingLogFactorialRemainder(20.0), 4.16631969199692246e-3, + 2e-15); + EXPECT_NEAR(StirlingLogFactorialRemainder(25.0), 3.33315563672809288e-3, + 2e-15); + EXPECT_NEAR(StirlingLogFactorialRemainder(50.0), 1.66664444698336551e-3, + 2e-15); + EXPECT_NEAR(StirlingLogFactorialRemainder(100.0), 8.33330555634914683e-4, + 2e-15); + EXPECT_NEAR(StirlingLogFactorialRemainder(1000.0), 8.33333305555563492e-5, + 2e-15); +} + +TEST(FastMathTest, StirlingLogFactorialRemainderSatisfiesTelescopingIdentity) { + using absl::random_internal::StirlingLogFactorialRemainder; + + // R(k) - R(k + 1) = (k + 0.5) * ln((k + 1) / k) - 1 + // = sum_{m >= 1} 1 / ((2m + 1) * (2k + 1)^(2m)). + for (int k = 20; k < 100; ++k) { + const double d = static_cast<double>(k); + const double z = 1.0 / (2.0 * d + 1.0); + const double z2 = z * z; + double expected_diff = 0.0; + double z_pow = z2; + for (int m = 1; m <= 6; ++m) { + expected_diff += z_pow / static_cast<double>(2 * m + 1); + z_pow *= z2; + } + EXPECT_NEAR( + StirlingLogFactorialRemainder(d) - StirlingLogFactorialRemainder(d + 1), + expected_diff, 2e-15); + } +} + +TEST(FastMathTest, StirlingLogFactorialRemainderAgreesWithLgamma) { + using absl::random_internal::StirlingLogFactorialRemainder; + + // Tolerance allows ~44 bits of cancellation in lgamma(d + 1) - (d + 0.5) * + // log(d). + constexpr double kLog2PI = 1.83787706640934548356; + for (int i = 20; i < 100; ++i) { + const double d = static_cast<double>(i); + const double expected = + std::lgamma(d + 1.0) - ((d + 0.5) * std::log(d) - d + 0.5 * kLog2PI); + EXPECT_NEAR(StirlingLogFactorialRemainder(d), expected, 1e-12); + } +} + } // namespace
diff --git a/absl/random/poisson_distribution.cc b/absl/random/poisson_distribution.cc new file mode 100644 index 0000000..3ec53aa --- /dev/null +++ b/absl/random/poisson_distribution.cc
@@ -0,0 +1,89 @@ +// Copyright 2026 The Abseil Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "absl/random/poisson_distribution.h" + +#include <cassert> +#include <cmath> + +#include "absl/base/config.h" +#include "absl/random/internal/fastmath.h" + +namespace absl { +ABSL_NAMESPACE_BEGIN +namespace random_internal { + +double PoissonLogRatioTerm(double x, double d, double mean) { + assert(std::isfinite(x) && x >= 20.0); + assert(std::isfinite(mean) && mean > 0.0); + const double s = x + mean; + const double y = d / s; + const double rem = StirlingLogFactorialRemainder(x); + if (std::abs(y) <= 0.1) { + // Use ln(mean / x) = -2 * (y + y^3/3 + y^5/5 + ...), where the linear + // terms in (x + 0.5) * ln(mean / x) + (x - mean) cancel algebraically: + // -(d + 1) * y - (2 * x + 1) * y^3 * (1/3 + y^2/5 + ...). + // For |y| <= 0.1, the omitted inner series remainder is + // < 0.1^17 / (17 * 0.99) < 1e-18, giving relative truncation error + // < 1e-16 (< 0.5 ULP) in g(x, mean) after scaling by 2 * x + 1. + const double y2 = y * y; + const double poly = + (1.0 / 3.0) + + y2 * ((1.0 / 5.0) + + y2 * ((1.0 / 7.0) + + y2 * ((1.0 / 9.0) + + y2 * ((1.0 / 11.0) + + y2 * ((1.0 / 13.0) + y2 * (1.0 / 15.0)))))); + return -(d + 1.0) * y - (2.0 * x + 1.0) * (y * y2) * poly - rem; + } + return (x + 0.5) * std::log(mean / x) + d - rem; +} + +double PoissonLogRatio(double x, double d, double mean, double lmu, + double g_mode) { + assert(std::isfinite(x) && x >= 0.0 && x == std::floor(x)); + if (x < 20.0) { + // Exact ln(k!) for k = 0..19. + static constexpr double kLogFactorial[20] = { + 0.0, + 0.0, + 0.69314718055994530942, + 1.79175946922805500081, + 3.17805383034794561965, + 4.78749174278204599425, + 6.57925121201010099506, + 8.52516136106541430017, + 10.60460290274525022842, + 12.80182748008146961121, + 15.10441257307551529523, + 17.50230784587388583929, + 19.98721449566188614952, + 22.55216385312342288557, + 25.19122118273868150009, + 27.89927138384089156609, + 30.67186010608067280376, + 33.50507345013688888401, + 36.39544520803305357622, + 39.33988418719949403622, + }; + constexpr double kLog2PI = 1.83787706640934548356; + return x * lmu - mean - kLogFactorial[static_cast<int>(x)] + + 0.5 * (kLog2PI + lmu) - g_mode; + } + return PoissonLogRatioTerm(x, d, mean) - g_mode; +} + +} // namespace random_internal +ABSL_NAMESPACE_END +} // namespace absl
diff --git a/absl/random/poisson_distribution.h b/absl/random/poisson_distribution.h index 16ab7ab..5199402 100644 --- a/absl/random/poisson_distribution.h +++ b/absl/random/poisson_distribution.h
@@ -24,8 +24,8 @@ #include <ostream> #include "absl/base/config.h" +#include "absl/random/bernoulli_distribution.h" #include "absl/random/internal/fast_uniform_bits.h" -#include "absl/random/internal/fastmath.h" #include "absl/random/internal/generate_real.h" #include "absl/random/internal/iostream_state_saver.h" #include "absl/random/internal/traits.h" @@ -34,8 +34,24 @@ ABSL_NAMESPACE_BEGIN namespace random_internal { -// Maximum supported mean for absl::poisson_distribution::param_type. -inline constexpr double kPoissonMaxMean = 1e10; +// Ratio-of-uniforms computes variates in IEEE-754 `double`, which represents +// consecutive integers exactly up to 2^53 (~9e15). Cap `mean` at 1e15 so that +// variates around `mean` preserve unit integer resolution. +inline constexpr double kPoissonMaxMean = 1e15; + +// Computes g(x, mean) = (x + 0.5) * ln(mean / x) + (x - mean) - R(x) for +// x >= 20 and mean > 0, where d = x - mean and R(x) is the Stirling +// log-factorial remainder. Because ln(P(X = x)) = g(x, mean) - +// 0.5 * ln(2 * pi * mean), the difference g(x, mean) - g(mode, mean) equals +// ln(P(X = x) / P(X = mode)) without subtracting large O(mean * ln(mean)) +// terms. +double PoissonLogRatioTerm(double x, double d, double mean); + +// Computes ln(P(X = x) / P(X = mode)) for integer x >= 0 and mean > 20 +// (so mode = ceil(mean) - 1 >= 20), given d = x - mean, lmu = ln(mean), and +// g_mode = PoissonLogRatioTerm(mode, mode - mean, mean). +double PoissonLogRatio(double x, double d, double mean, double lmu, + double g_mode); } // namespace random_internal @@ -45,11 +61,13 @@ // // Depending on the parameter, the distribution selects one of the following // algorithms: +// * Exact arrival-time thinning via -expm1(-mean) for tiny values +// (mean < 1e-4). // * The standard algorithm, attributed to Knuth, extended using a split method -// for larger values +// for larger values (1e-4 <= mean <= 50). // * The "Ratio of Uniforms as a convenient method for sampling from classical -// discrete distributions", Stadlober, 1989. -// http://www.sciencedirect.com/science/article/pii/0377042790903495 +// discrete distributions", Stadlober, 1989 (mean > 50). +// http://www.sciencedirect.com/science/article/pii/0377042790903495 // // NOTE: param_type.mean() is a double, which permits values larger than // poisson_distribution<IntType>::max(), however this should be avoided and @@ -83,11 +101,11 @@ friend class poisson_distribution; double mean_; - double emu_; // e ^ -mean_ - double lmu_; // ln(mean_) - double s_; - double log_k_; - int split_; + double emu_; // exp(-mean_) for Knuth, -expm1(-mean_) for tiny mean + double lmu_; // ln(mean_) + double s_; // ratio-of-uniforms envelope scale + double g_mode_; // g(mode, mean_) for ratio-of-uniforms + int split_; // -1: tiny mean, 0: ratio-of-uniforms, >0: Knuth splits static_assert(random_internal::IsIntegral<IntType>::value, "Class-template absl::poisson_distribution<> must be " @@ -140,15 +158,18 @@ template <typename IntType> poisson_distribution<IntType>::param_type::param_type(double mean) - : mean_(mean), split_(0) { + : mean_(mean), emu_(0.0), lmu_(0.0), s_(0.0), g_mode_(0.0), split_(0) { assert(mean >= 0); assert(mean <= static_cast<double>((std::numeric_limits<result_type>::max)())); - // As a defensive measure, avoid large values of the mean. The rejection - // algorithm used does not support very large values well. It my be worth - // changing algorithms to better deal with these cases. assert(mean <= random_internal::kPoissonMaxMean); - if (mean_ < 10) { + if (mean_ < 1e-4) { + // For tiny lambda, exp(-lambda) loses relative precision near 1.0 (and + // rounds to >= 1 - 2^-53 for lambda < 1.665e-16). Use exact Bernoulli + + // arrival-time thinning via -expm1(-lambda). + split_ = -1; + emu_ = mean_ <= 0.0 ? 0.0 : -std::expm1(-mean_); + } else if (mean_ < 10) { // For small lambda, use the knuth method. split_ = 1; emu_ = std::exp(-mean_); @@ -164,8 +185,8 @@ lmu_ = std::log(mean_); double a = mean_ + 0.5; s_ = kSA + std::sqrt(k2E * a); - const double mode = std::ceil(mean_) - 1; - log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode); + const double mode = std::ceil(mean_) - 1.0; + g_mode_ = random_internal::PoissonLogRatioTerm(mode, mode - mean_, mean_); } } @@ -179,10 +200,32 @@ using random_internal::GenerateRealFromBits; using random_internal::GenerateSignedTag; - if (p.split_ != 0) { + if (p.split_ < 0) { + // Exact Poisson sampling for tiny mean (< 1e-4) via arrival-time thinning: + // P(X >= 1) = 1 - exp(-mean) = -expm1(-mean). Conditional on X >= 1, the + // first arrival time T1 satisfies rem = mean - T1 = log1p(V * expm1(mean)) + // for V ~ Uniform[0, 1), and (X - 1 | T1) ~ Poisson(rem). + if (p.mean_ <= 0.0) return 0; + const result_type max_n = (max)(); + result_type n = 0; + double rem = p.mean_; + double prob = p.emu_; + while (bernoulli_distribution(prob)(g)) { + ++n; + if (n == max_n) return max_n; + const double v = + GenerateRealFromBits<double, GeneratePositiveTag, true>(fast_u64_(g)); + rem = std::log1p(v * std::expm1(rem)); + if (rem == 0.0) break; + prob = -std::expm1(-rem); + } + return n; + } + + if (p.split_ > 0) { // Use Knuth's algorithm with range splitting to avoid floating-point // errors. Knuth's algorithm is: Ui is a sequence of uniform variates on - // (0,1); return the number of variates required for product(Ui) < + // [0, 1); return the number of variates required for product(Ui) <= // exp(-lambda). // // The expected number of variates required for Knuth's method can be @@ -193,17 +236,27 @@ // lambda = [2, 5, 9, 10, 11, 12, 13, 14, 15, 16, 17] // n = [3, 8, 13, 15, 16, 18, 19, 21, 22, 24, 25] // - result_type n = 0; + // Accumulate in uint64_t to avoid overflow in the inner loop. For narrow + // types (<= 16-bit), exit early once n exceeds max() so a URBG returning + // values near 1 terminates promptly. + uint64_t n = 0; for (int split = p.split_; split > 0; --split) { double r = 1.0; do { r *= GenerateRealFromBits<double, GeneratePositiveTag, true>( - fast_u64_(g)); // U(-1, 0) + fast_u64_(g)); // U[0, 1) ++n; + if constexpr (std::numeric_limits<result_type>::digits <= 16) { + if (n > static_cast<uint64_t>((max)())) return (max)(); + } } while (r > p.emu_); --n; } - return n; + if constexpr (std::numeric_limits<result_type>::digits < + std::numeric_limits<uint64_t>::digits) { + if (n > static_cast<uint64_t>((max)())) return (max)(); + } + return static_cast<result_type>(n); } // Use ratio of uniforms method. @@ -215,26 +268,31 @@ // P(floor(x) = k | u^2 < f(floor(x))/k), where // f(m) = lambda^m exp(-lambda)/ m!, for 0 <= m, and f(m) = 0 otherwise, // and k = max(f). - const double a = p.mean_ + 0.5; + const double a_int = std::floor(p.mean_); + const double mean_frac = p.mean_ - a_int; + const double a_frac = mean_frac + 0.5; + const double min_dx = -(p.mean_ + 1.0); + const double max_dx = p.mean_ + 2000.0; for (;;) { const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>( fast_u64_(g)); // U(0, 1) const double v = GenerateRealFromBits<double, GenerateSignedTag, false>( fast_u64_(g)); // U(-1, 1) - const double x = std::floor(p.s_ * v / u + a); + // Reject extreme proposals before dividing by `u` so small `u` cannot + // overflow `sv / u` or `PoissonLogRatio` + const double sv = p.s_ * v; + if (sv < min_dx * u || sv > max_dx * u) continue; + const double dx = std::floor(sv / u + a_frac); + const double x = a_int + dx; if (x < 0) continue; // f(negative) = 0 - const double rhs = x * p.lmu_; - // clang-format off - double s = (x <= 1.0) ? 0.0 - : (x == 2.0) ? 0.693147180559945 - : absl::random_internal::StirlingLogFactorial(x); - // clang-format on - const double lhs = 2.0 * std::log(u) + p.log_k_ + s; - if (lhs < rhs) { - return x > static_cast<double>((max)()) - ? (max)() - : static_cast<result_type>(x); // f(x)/k >= u^2 + if (2.0 * std::log(u) < random_internal::PoissonLogRatio(x, dx - mean_frac, + p.mean_, p.lmu_, + p.g_mode_)) { + constexpr double kMax = + static_cast<double>((std::numeric_limits<result_type>::max)()); + // Clamp result to max(). + return x >= kMax ? (max)() : static_cast<result_type>(x); } } }
diff --git a/absl/random/poisson_distribution_test.cc b/absl/random/poisson_distribution_test.cc index 4bdcf72..f00f673 100644 --- a/absl/random/poisson_distribution_test.cc +++ b/absl/random/poisson_distribution_test.cc
@@ -18,8 +18,10 @@ #include <cmath> #include <cstddef> #include <cstdint> +#include <initializer_list> #include <iterator> #include <limits> +#include <ostream> #include <random> #include <sstream> #include <string> @@ -30,6 +32,7 @@ #include "absl/base/macros.h" #include "absl/container/flat_hash_map.h" #include "absl/log/log.h" +#include "absl/numeric/int128.h" #include "absl/random/internal/chi_square.h" #include "absl/random/internal/distribution_test_util.h" #include "absl/random/internal/pcg_engine.h" @@ -64,7 +67,14 @@ namespace { -using absl::random_internal::kChiSquared; +using ::absl::random_internal::kChiSquared; +using ::testing::AllOf; +using ::testing::Contains; +using ::testing::DoubleNear; +using ::testing::Each; +using ::testing::ElementsAre; +using ::testing::Ge; +using ::testing::Le; // The PoissonDistributionInterfaceTest provides a basic test that // absl::poisson_distribution conforms to the interface and serialization @@ -73,14 +83,15 @@ template <typename IntType> class PoissonDistributionInterfaceTest : public ::testing::Test {}; -using IntTypes = ::testing::Types<int, int8_t, int16_t, int32_t, int64_t, - uint8_t, uint16_t, uint32_t, uint64_t>; +using IntTypes = + ::testing::Types<int, int8_t, int16_t, int32_t, int64_t, absl::int128, + uint8_t, uint16_t, uint32_t, uint64_t, absl::uint128>; TYPED_TEST_SUITE(PoissonDistributionInterfaceTest, IntTypes); TYPED_TEST(PoissonDistributionInterfaceTest, SerializeTest) { using param_type = typename absl::poisson_distribution<TypeParam>::param_type; const double kMax = - std::min(1e10 /* assertion limit */, + std::min(1e15 /* assertion limit */, static_cast<double>(std::numeric_limits<TypeParam>::max())); const double kParams[] = { @@ -89,13 +100,18 @@ std::nextafter(1.0, 0.0), // 1 - epsilon std::nextafter(1.0, 2.0), // 1 + epsilon // Arbitrary values. - 1e-8, 1e-4, + 1e-8, + 1e-4, 0.0000005, // ~7.2e-7 0.2, // ~0.2x 0.5, // 0.72 2, // ~2.8 20, // 3x ~9.6 - 100, 1e4, 1e8, 1.5e9, 1e20, + 100, + 1e4, + 1e8, + 1.5e9, + 1e20, // Boundary cases. std::numeric_limits<double>::max(), std::numeric_limits<double>::epsilon(), @@ -475,15 +491,16 @@ } INSTANTIATE_TEST_SUITE_P(All, PoissonDistributionChiSquaredTest, - ::testing::Values(0.5, 1.0, 2.0, 10.0, 50.0, 51.0, - 200.0)); + ::testing::Values(0.5, 1.0, 2.0, 10.0, 50.0, + std::nextafter(50.0, 51.0), 51.0, + 51.5, 200.0)); // NOTE: absl::poisson_distribution is not guaranteed to be stable. TEST(PoissonDistributionTest, StabilityTest) { - using testing::ElementsAre; // absl::poisson_distribution stability relies on stability of - // std::exp, std::log, std::sqrt, std::ceil, std::floor, and - // absl::FastUniformBits, absl::StirlingLogFactorial, absl::RandU64ToDouble. + // std::exp, std::expm1, std::log, std::log1p, std::sqrt, std::ceil, + // std::floor, FastUniformBits, GenerateRealFromBits, and + // StirlingLogFactorialRemainder. absl::random_internal::sequence_urbg urbg({ 0x035b0dc7e0a18acfull, 0x06cebe0d2653682eull, 0x0061e9b23861596bull, 0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, @@ -585,6 +602,8 @@ const absl::poisson_distribution<int8_t> kI8Initial(4.5); const absl::poisson_distribution<uint8_t> kU8Initial(4.5); const absl::poisson_distribution<int64_t> kI64Initial(4.5); + const absl::poisson_distribution<absl::int128> kI128Initial(4.5); + const absl::poisson_distribution<absl::uint128> kU128Initial(4.5); EXPECT_THAT(ParseFromStream(kInitial, ""), FailsLeavingUnchanged()); EXPECT_THAT(ParseFromStream(kInitial, "abc"), FailsLeavingUnchanged()); @@ -621,6 +640,460 @@ EXPECT_THAT(ParseFromStream(kI64Initial, absl::StrCat(kMaxMean * 10.0)), FailsLeavingUnchanged()); EXPECT_THAT(ParseFromStream(kI64Initial, "1e20"), FailsLeavingUnchanged()); + + EXPECT_THAT( + ParseFromStream(kI128Initial, absl::StrCat(kMaxMean)), + ParsesEqualTo(absl::poisson_distribution<absl::int128>(kMaxMean))); + EXPECT_THAT(ParseFromStream(kI128Initial, "1e20"), FailsLeavingUnchanged()); + EXPECT_THAT( + ParseFromStream(kU128Initial, absl::StrCat(kMaxMean)), + ParsesEqualTo(absl::poisson_distribution<absl::uint128>(kMaxMean))); + EXPECT_THAT(ParseFromStream(kU128Initial, "1e20"), FailsLeavingUnchanged()); +} + +// Fixed seed for deterministic sampling tests (fractional hex digits of Euler's +// number e, matching PoissonDistributionZTest above). +constexpr uint64_t kTestSeed = 0x2B7E151628AED2A6ULL; + +template <typename IntType> +IntType SamplePoissonWithBits(double mean, + std::initializer_list<uint64_t> seq) { + absl::random_internal::sequence_urbg urbg(seq); + absl::poisson_distribution<IntType> dist(mean); + return dist(urbg); +} + +template <typename IntType> +std::vector<IntType> DrawPoissonSamples(double mean, size_t count) { + absl::random_internal::pcg64_2018_engine rng(kTestSeed); + absl::poisson_distribution<IntType> dist(mean); + std::vector<IntType> samples(count); + std::generate(samples.begin(), samples.end(), [&] { return dist(rng); }); + return samples; +} + +template <typename IntType> +struct PoissonSampleSummary { + IntType min_sample; + IntType max_sample; + size_t nonzero_count; + double mean; +}; + +template <typename IntType> +void PrintTo(const PoissonSampleSummary<IntType>& s, std::ostream* os) { + *os << "{min_sample=" << +s.min_sample << ", max_sample=" << +s.max_sample + << ", nonzero_count=" << s.nonzero_count << ", mean=" << s.mean << "}"; +} + +template <typename IntType> +PoissonSampleSummary<IntType> SummarizePoissonSamples( + double mean, size_t count, uint64_t seed = kTestSeed) { + absl::random_internal::pcg64_2018_engine rng(seed); + absl::poisson_distribution<IntType> dist(mean); + IntType min_s = dist.max(); + IntType max_s = dist.min(); + size_t nonzero = 0; + double sum = 0.0; + for (size_t i = 0; i < count; ++i) { + const IntType x = dist(rng); + min_s = (std::min)(min_s, x); + max_s = (std::max)(max_s, x); + if (x > 0) { + ++nonzero; + } + sum += static_cast<double>(x); + } + return {min_s, max_s, nonzero, sum / static_cast<double>(count)}; +} + +MATCHER_P2(HasPositiveNonZeroAndMeanNear, expected_mean, tol, "") { + using SampleType = decltype(arg.min_sample); + if constexpr (std::numeric_limits<SampleType>::is_signed) { + if (arg.min_sample < SampleType{0}) return false; + } + return arg.nonzero_count > 0 && std::abs(arg.mean - expected_mean) <= tol; +} + +struct PoissonDrawResult { + int64_t sample; + size_t rng_draws; +}; + +void PrintTo(const PoissonDrawResult& r, std::ostream* os) { + *os << "{sample=" << r.sample << ", rng_draws=" << r.rng_draws << "}"; +} + +PoissonDrawResult DrawLargeMeanSequence(double mean, + std::initializer_list<uint64_t> seq) { + absl::random_internal::sequence_urbg urbg(seq); + absl::poisson_distribution<int64_t> dist(mean); + const int64_t sample = dist(urbg); + return {sample, urbg.invocations()}; +} + +MATCHER_P2(ProducesSampleInDraws, expected_sample, expected_draws, "") { + return arg.sample == expected_sample && + arg.rng_draws == static_cast<size_t>(expected_draws); +} + +struct OffsetMomentsSummary { + double abs_z_score; + double variance; +}; + +void PrintTo(const OffsetMomentsSummary& s, std::ostream* os) { + *os << "{abs_z_score=" << s.abs_z_score << ", variance=" << s.variance << "}"; +} + +OffsetMomentsSummary SummarizeLargeMeanOffsets(double mean, + uint64_t seed = kTestSeed) { + constexpr size_t kSamples = 50000; + absl::random_internal::pcg64_2018_engine rng(seed); + absl::poisson_distribution<int64_t> dist(mean); + std::vector<double> offsets(kSamples); + for (size_t i = 0; i < kSamples; ++i) { + offsets[i] = static_cast<double>(dist(rng)) - mean; + } + const auto m = absl::random_internal::ComputeDistributionMoments(offsets); + return {std::abs(absl::random_internal::ZScore(0.0, m)), m.variance}; +} + +MATCHER_P2(HasUnbiasedMomentsWithVarianceNear, expected_var, rel_tol, "") { + return arg.abs_z_score < 4.0 && + std::abs(arg.variance - expected_var) <= expected_var * rel_tol; +} + +double EvalPoissonLogRatio(double x, double mean) { + const double mode = std::ceil(mean) - 1.0; + const double g_mode = + absl::random_internal::PoissonLogRatioTerm(mode, mode - mean, mean); + return absl::random_internal::PoissonLogRatio(x, x - mean, mean, + std::log(mean), g_mode); +} + +double ExactLgammaLogRatio(double x, double mean) { + const double mode = std::ceil(mean) - 1.0; + return (x - mode) * std::log(mean) - + (std::lgamma(x + 1.0) - std::lgamma(mode + 1.0)); +} + +class RepeatMaxThenZeroUrbg { + public: + using result_type = uint64_t; + static constexpr result_type(min)() { return 0; } + static constexpr result_type(max)() { return ~uint64_t{0}; } + explicit RepeatMaxThenZeroUrbg(size_t max_draws) : remaining_(max_draws) {} + result_type operator()() { + if (remaining_ == 0) return 0; + --remaining_; + return ~uint64_t{0}; + } + + private: + size_t remaining_; +}; + +template <typename IntType> +IntType SamplePoissonAfterRepeatedMaxBits(double mean, size_t max_bit_draws) { + RepeatMaxThenZeroUrbg urbg(max_bit_draws); + absl::poisson_distribution<IntType> dist(mean); + return dist(urbg); +} + +// ---------------------------------------------------------------------------- +// The following tests verify algorithm behavior and boundary cases. +// ---------------------------------------------------------------------------- + +TEST(PoissonDistributionTest, Int8KnuthClampsAtMax) { + // All-ones bits yield U = 1 - 2^-53, driving Knuth accumulation to int8 max. + EXPECT_EQ(SamplePoissonWithBits<int8_t>(50.0, {~uint64_t{0}}), + (std::numeric_limits<int8_t>::max)()); +} + +TEST(PoissonDistributionTest, Uint8KnuthClampsAtMax) { + // All-ones bits yield U = 1 - 2^-53, driving Knuth accumulation to uint8 max. + EXPECT_EQ(SamplePoissonWithBits<uint8_t>(50.0, {~uint64_t{0}}), + (std::numeric_limits<uint8_t>::max)()); +} + +TEST(PoissonDistributionTest, Int8KnuthBoundaryDoesNotOverflow) { + // 127 max-bit draws followed by 0ULL at mean = 5.0 => 127 + EXPECT_EQ(SamplePoissonAfterRepeatedMaxBits<int8_t>(5.0, 126), int8_t{126}); + EXPECT_EQ(SamplePoissonAfterRepeatedMaxBits<int8_t>(5.0, 127), int8_t{127}); + EXPECT_EQ(SamplePoissonAfterRepeatedMaxBits<int8_t>(5.0, 128), int8_t{127}); +} + +TEST(PoissonDistributionTest, Uint8KnuthBoundaryDoesNotWrap) { + // 256 max-bit draws followed by 0ULL at mean = 5.0 => 255 + EXPECT_EQ(SamplePoissonAfterRepeatedMaxBits<uint8_t>(5.0, 254), uint8_t{254}); + EXPECT_EQ(SamplePoissonAfterRepeatedMaxBits<uint8_t>(5.0, 255), uint8_t{255}); + EXPECT_EQ(SamplePoissonAfterRepeatedMaxBits<uint8_t>(5.0, 256), uint8_t{255}); +} + +TEST(PoissonDistributionTest, Int8RatioOfUniformsNearMaxStaysInBounds) { + EXPECT_THAT(DrawPoissonSamples<int8_t>(127.0, 2000), + AllOf(Each(Ge(int8_t{60})), Contains(int8_t{127}))); +} + +TEST(PoissonDistributionTest, Uint8RatioOfUniformsNearMaxStaysInBounds) { + EXPECT_THAT(DrawPoissonSamples<uint8_t>(255.0, 2000), + AllOf(Each(Ge(uint8_t{150})), Contains(uint8_t{255}))); +} + +TEST(PoissonDistributionTest, Int128AndUint128TinyMeanSampling) { + EXPECT_EQ(SamplePoissonWithBits<absl::int128>(1e-20, {0ULL}), + absl::int128{1}); + EXPECT_EQ(SamplePoissonWithBits<absl::int128>(1e-20, {~uint64_t{0}}), + absl::int128{0}); + EXPECT_EQ(SamplePoissonWithBits<absl::uint128>(1e-20, {0ULL}), + absl::uint128{1}); + EXPECT_EQ(SamplePoissonWithBits<absl::uint128>(1e-20, {~uint64_t{0}}), + absl::uint128{0}); +} + +TEST(PoissonDistributionTest, Int128AndUint128KnuthSampling) { + EXPECT_EQ(SamplePoissonWithBits<absl::int128>(5.0, {0x8000000000000001ULL}), + absl::int128{7}); + EXPECT_EQ(SamplePoissonWithBits<absl::int128>(25.0, {0x8000000000000001ULL}), + absl::int128{36}); + EXPECT_EQ(SamplePoissonWithBits<absl::uint128>(5.0, {0x8000000000000001ULL}), + absl::uint128{7}); + EXPECT_EQ(SamplePoissonWithBits<absl::uint128>(25.0, {0x8000000000000001ULL}), + absl::uint128{36}); +} + +TEST(PoissonDistributionTest, Int128AndUint128LargeMeanSampling) { + constexpr uint64_t kUMax = ~uint64_t{0}; + EXPECT_EQ(SamplePoissonWithBits<absl::int128>(1e15, {kUMax, 0ULL}), + absl::int128{1'000'000'000'000'000LL}); + EXPECT_EQ(SamplePoissonWithBits<absl::uint128>(1e15, {kUMax, 0ULL}), + absl::uint128{1'000'000'000'000'000ULL}); + + constexpr absl::int128 kI128Lo = absl::int128{999'000'000'000'000LL}; + constexpr absl::int128 kI128Hi = absl::int128{1'001'000'000'000'000LL}; + EXPECT_THAT(DrawPoissonSamples<absl::int128>(1e15, 1000), + Each(AllOf(Ge(kI128Lo), Le(kI128Hi)))); + + constexpr absl::uint128 kU128Lo = absl::uint128{999'000'000'000'000ULL}; + constexpr absl::uint128 kU128Hi = absl::uint128{1'001'000'000'000'000ULL}; + EXPECT_THAT(DrawPoissonSamples<absl::uint128>(1e15, 1000), + Each(AllOf(Ge(kU128Lo), Le(kU128Hi)))); +} + +TEST(PoissonDistributionTest, ZeroMeanAlwaysReturnsZero) { + EXPECT_EQ(SamplePoissonWithBits<int>(0.0, {0ULL}), 0); + EXPECT_THAT(DrawPoissonSamples<uint64_t>(0.0, 1000), Each(uint64_t{0})); +} + +#ifdef NDEBUG +TEST(PoissonDistributionTest, NegativeMeanReturnsZeroInNdebug) { + EXPECT_EQ(SamplePoissonWithBits<int>(-1e-9, {0ULL}), 0); + EXPECT_EQ(SamplePoissonWithBits<int>(-1.0, {0ULL}), 0); + EXPECT_EQ(SamplePoissonWithBits<int>(-22.0, {0ULL}), 0); + EXPECT_EQ(SamplePoissonWithBits<int>(-1000.0, {0ULL}), 0); + EXPECT_EQ(SamplePoissonWithBits<int8_t>(-1.0, {0ULL}), int8_t{0}); + EXPECT_EQ(SamplePoissonWithBits<int64_t>(-1000.0, {0ULL}), int64_t{0}); +} +#endif + +TEST(PoissonDistributionTest, TinyMeanClampsAtMaxForNarrowInts) { + // Alternating 0ULL (accepts Bernoulli at 9e-5) and ~0ULL (v = 1 - 2^-53, + // keeping rem near 9e-5) drives arrival-time thinning to max(). + EXPECT_EQ(SamplePoissonWithBits<int8_t>(9e-5, {0ULL, ~uint64_t{0}}), + (std::numeric_limits<int8_t>::max)()); + EXPECT_EQ(SamplePoissonWithBits<uint8_t>(9e-5, {0ULL, ~uint64_t{0}}), + (std::numeric_limits<uint8_t>::max)()); +} + +TEST(PoissonDistributionTest, Uint64SingleStepKnuthMeanIsAccurate) { + EXPECT_THAT(SummarizePoissonSamples<uint64_t>(1.0, 20000), + HasPositiveNonZeroAndMeanNear(1.0, 0.05)); + EXPECT_THAT(SummarizePoissonSamples<uint64_t>(5.0, 20000), + HasPositiveNonZeroAndMeanNear(5.0, 0.1)); +} + +TEST(PoissonDistributionTest, Uint64SplitKnuthMeanIsAccurate) { + EXPECT_THAT(SummarizePoissonSamples<uint64_t>(20.0, 20000), + HasPositiveNonZeroAndMeanNear(20.0, 0.2)); + EXPECT_THAT(SummarizePoissonSamples<uint64_t>(50.0, 20000), + HasPositiveNonZeroAndMeanNear(50.0, 0.3)); +} + +TEST(PoissonDistributionTest, TinyMeanZeroBitsReturnsOne) { + EXPECT_EQ(SamplePoissonWithBits<int>(1e-18, {0ULL}), 1); + EXPECT_EQ(SamplePoissonWithBits<uint64_t>(1e-20, {0ULL}), uint64_t{1}); +} + +TEST(PoissonDistributionTest, SubnormalMeanZeroBitsReturnsOne) { + EXPECT_EQ(SamplePoissonWithBits<int64_t>( + std::numeric_limits<double>::denorm_min(), {0ULL}), + int64_t{1}); +} + +TEST(PoissonDistributionTest, TinyMeanMaxBitsReturnsZero) { + EXPECT_EQ(SamplePoissonWithBits<uint64_t>(1e-20, {~uint64_t{0}}), + uint64_t{0}); +} + +TEST(PoissonDistributionTest, TinyMeanCanSampleCountTwo) { + // Arrival-time thinning reaches X >= 2 rather than truncating to {0, 1}. + EXPECT_EQ(SamplePoissonWithBits<uint64_t>( + 1e-20, {0ULL, 0ULL, 0ULL, 0x8000000000000000ULL, 0ULL, 0ULL, + 0ULL, 0ULL}), + uint64_t{2}); +} + +TEST(PoissonDistributionTest, TinyMeanStatisticalRateMatchesMean) { + constexpr double kTinyMean = 9e-5; + constexpr size_t kSamples = 200000; + + EXPECT_THAT(SummarizePoissonSamples<int>(kTinyMean, kSamples), + HasPositiveNonZeroAndMeanNear(kTinyMean, 4.5e-5)); +} + +TEST(PoissonDistributionTest, LargeIntegerMeanAcceptsUpperAndLowerModes) { + constexpr uint64_t kUMax = ~uint64_t{0}; + constexpr uint64_t kNegPow2Minus17 = + (uint64_t{1} << 63) | (uint64_t{1} << (63 - 17)); + + // Integer means have dual modes at mean and mean - 1, both accepted at + // u = 1 - 2^-53 on the first proposal (2 URBG draws). + EXPECT_THAT(DrawLargeMeanSequence(1e10, {kUMax, 0ULL}), + ProducesSampleInDraws(10'000'000'000LL, 2)); + EXPECT_THAT(DrawLargeMeanSequence(1e10, {kUMax, kNegPow2Minus17}), + ProducesSampleInDraws(9'999'999'999LL, 2)); + EXPECT_THAT(DrawLargeMeanSequence(1e12, {kUMax, 0ULL}), + ProducesSampleInDraws(1'000'000'000'000LL, 2)); + EXPECT_THAT(DrawLargeMeanSequence(1e15, {kUMax, 0ULL}), + ProducesSampleInDraws(1'000'000'000'000'000LL, 2)); +} + +TEST(PoissonDistributionTest, FractionalLargeMeanAcceptsModeOnFirstProposal) { + constexpr uint64_t kUMax = ~uint64_t{0}; + constexpr uint64_t kNegPow2Minus25 = + (uint64_t{1} << 63) | (uint64_t{1} << (63 - 25)); + const double kMaxFracMean = std::nextafter(1e15, 0.0); + + EXPECT_THAT(DrawLargeMeanSequence(51.5, {kUMax, kNegPow2Minus25}), + ProducesSampleInDraws(51, 2)); + EXPECT_THAT(DrawLargeMeanSequence(1e10 + 0.375, {kUMax, 0ULL}), + ProducesSampleInDraws(10'000'000'000LL, 2)); + EXPECT_THAT(DrawLargeMeanSequence(kMaxFracMean, {kUMax, kNegPow2Minus25}), + ProducesSampleInDraws(999'999'999'999'999LL, 2)); +} + +TEST(PoissonDistributionTest, FractionalLargeMeanRejectsOffModeAtMaxUniform) { + constexpr uint64_t kUMax = ~uint64_t{0}; + constexpr uint64_t kNegPow2Minus25 = + (uint64_t{1} << 63) | (uint64_t{1} << (63 - 25)); + constexpr uint64_t kNegPow2Minus2 = + (uint64_t{1} << 63) | (uint64_t{1} << (63 - 2)); + + // For mean = 51.5 (unique mode 51), off-mode proposals dx = +1 (0ULL) and + // dx = -1 (-0.25) reject at u = 1 - 2^-53 before accepting dx = 0 on the + // second iteration (4 URBG draws). + EXPECT_THAT( + DrawLargeMeanSequence(51.5, {kUMax, 0ULL, kUMax, kNegPow2Minus25}), + ProducesSampleInDraws(51, 4)); + EXPECT_THAT(DrawLargeMeanSequence( + 51.5, {kUMax, kNegPow2Minus2, kUMax, kNegPow2Minus25}), + ProducesSampleInDraws(51, 4)); +} + +class PoissonLargeMeanMomentsTest : public ::testing::TestWithParam<double> {}; + +TEST_P(PoissonLargeMeanMomentsTest, OffsetMomentsAreUnbiased) { + const double mean = GetParam(); + EXPECT_THAT(SummarizeLargeMeanOffsets(mean), + HasUnbiasedMomentsWithVarianceNear(mean, 0.025)); +} + +INSTANTIATE_TEST_SUITE_P(All, PoissonLargeMeanMomentsTest, + ::testing::Values(51.5, 1e10, 1e10 + 0.375, 1e12, 1e15, + std::nextafter(1e15, 0.0))); + +TEST(PoissonDistributionTest, LogRatioMatchesLgammaAcrossTableBoundary) { + for (const double mean : {51.0, 51.5}) { + EXPECT_THAT(EvalPoissonLogRatio(0.0, mean), + DoubleNear(ExactLgammaLogRatio(0.0, mean), 1e-12)); + EXPECT_THAT(EvalPoissonLogRatio(1.0, mean), + DoubleNear(ExactLgammaLogRatio(1.0, mean), 1e-12)); + EXPECT_THAT(EvalPoissonLogRatio(19.0, mean), + DoubleNear(ExactLgammaLogRatio(19.0, mean), 1e-12)); + EXPECT_THAT(EvalPoissonLogRatio(20.0, mean), + DoubleNear(ExactLgammaLogRatio(20.0, mean), 1e-12)); + } +} + +TEST(PoissonDistributionTest, LogRatioIsZeroAtBothModesForLargeIntegerMean) { + EXPECT_THAT(EvalPoissonLogRatio(1e10 - 1.0, 1e10), DoubleNear(0.0, 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(1e10, 1e10), DoubleNear(0.0, 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(1e12, 1e12), DoubleNear(0.0, 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(1e15, 1e15), DoubleNear(0.0, 1e-14)); +} + +TEST(PoissonDistributionTest, + LogRatioMatchesAdjacentStepsAtModerateFractionalMean) { + EXPECT_THAT(EvalPoissonLogRatio(50.0, 51.5), + DoubleNear(std::log(51.0 / 51.5), 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(51.0, 51.5), DoubleNear(0.0, 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(52.0, 51.5), + DoubleNear(std::log(51.5 / 52.0), 1e-14)); +} + +TEST(PoissonDistributionTest, + LogRatioMatchesAdjacentStepsAtLargeFractionalMean) { + constexpr double kFracMean1e10 = 1e10 + 0.375; + const double kMaxFracMean = std::nextafter(1e15, 0.0); + const double kMaxFracMode = std::ceil(kMaxFracMean) - 1.0; + const double kMaxFracPart = kMaxFracMean - kMaxFracMode; + + EXPECT_THAT(EvalPoissonLogRatio(1e10 - 1.0, kFracMean1e10), + DoubleNear(std::log1p(-0.375 / kFracMean1e10), 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(1e10, kFracMean1e10), DoubleNear(0.0, 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(1e10 + 1.0, kFracMean1e10), + DoubleNear(std::log1p(-0.625 / (1e10 + 1.0)), 1e-14)); + EXPECT_THAT(EvalPoissonLogRatio(kMaxFracMode - 1.0, kMaxFracMean), + DoubleNear(std::log1p(-kMaxFracPart / kMaxFracMean), 1e-17)); + EXPECT_THAT(EvalPoissonLogRatio(kMaxFracMode, kMaxFracMean), + DoubleNear(0.0, 1e-17)); + EXPECT_THAT( + EvalPoissonLogRatio(kMaxFracMode + 1.0, kMaxFracMean), + DoubleNear(std::log1p((kMaxFracPart - 1.0) / (kMaxFracMode + 1.0)), + 1e-17)); +} + +TEST(PoissonDistributionTest, RatioOfUniformsRejectsExtremeTailProposals) { + constexpr uint64_t kUMin = 0ULL; + constexpr uint64_t kUMax = ~uint64_t{0}; + constexpr uint64_t kVPosMax = 0x7fffffffffffffffULL; + constexpr uint64_t kVNegMax = ~uint64_t{0}; + + // Extreme proposals (u = 2^-65, v = +/-(1 - 2^-53)) are rejected by the + // pre-division bounds check before accepting the mode on iteration 2. + EXPECT_THAT(DrawLargeMeanSequence(51.0, {kUMin, kVPosMax, kUMax, 0ULL}), + ProducesSampleInDraws(51, 4)); + EXPECT_THAT(DrawLargeMeanSequence(51.0, {kUMin, kVNegMax, kUMax, 0ULL}), + ProducesSampleInDraws(51, 4)); + EXPECT_THAT(DrawLargeMeanSequence(1e15, {kUMin, kVPosMax, kUMax, 0ULL}), + ProducesSampleInDraws(1'000'000'000'000'000LL, 4)); + EXPECT_THAT(DrawLargeMeanSequence(1e15, {kUMin, kVNegMax, kUMax, 0ULL}), + ProducesSampleInDraws(1'000'000'000'000'000LL, 4)); +} + +TEST(PoissonDistributionTest, LogRatioContinuousAcrossSeriesBoundary) { + // At mean = 100, |y| = |x - mean| / (x + mean) crosses 0.1 between + // x = 81 (y = -0.1050) / x = 82 (y = -0.0989) and between + // x = 122 (y = 0.0991) / x = 123 (y = 0.1031). + EXPECT_THAT(EvalPoissonLogRatio(81.0, 100.0), + DoubleNear(ExactLgammaLogRatio(81.0, 100.0), 1e-12)); + EXPECT_THAT(EvalPoissonLogRatio(82.0, 100.0), + DoubleNear(ExactLgammaLogRatio(82.0, 100.0), 1e-12)); + EXPECT_THAT(EvalPoissonLogRatio(122.0, 100.0), + DoubleNear(ExactLgammaLogRatio(122.0, 100.0), 1e-12)); + EXPECT_THAT(EvalPoissonLogRatio(123.0, 100.0), + DoubleNear(ExactLgammaLogRatio(123.0, 100.0), 1e-12)); } } // namespace