uniform_int_distribution_test.cc 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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/uniform_int_distribution.h"
  15. #include <cmath>
  16. #include <cstdint>
  17. #include <iterator>
  18. #include <random>
  19. #include <sstream>
  20. #include <vector>
  21. #include "gmock/gmock.h"
  22. #include "gtest/gtest.h"
  23. #include "absl/base/internal/raw_logging.h"
  24. #include "absl/random/internal/chi_square.h"
  25. #include "absl/random/internal/distribution_test_util.h"
  26. #include "absl/random/internal/pcg_engine.h"
  27. #include "absl/random/internal/sequence_urbg.h"
  28. #include "absl/random/random.h"
  29. #include "absl/strings/str_cat.h"
  30. namespace {
  31. template <typename IntType>
  32. class UniformIntDistributionTest : public ::testing::Test {};
  33. using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t,
  34. uint32_t, int64_t, uint64_t>;
  35. TYPED_TEST_SUITE(UniformIntDistributionTest, IntTypes);
  36. TYPED_TEST(UniformIntDistributionTest, ParamSerializeTest) {
  37. // This test essentially ensures that the parameters serialize,
  38. // not that the values generated cover the full range.
  39. using Limits = std::numeric_limits<TypeParam>;
  40. using param_type =
  41. typename absl::uniform_int_distribution<TypeParam>::param_type;
  42. const TypeParam kMin = std::is_unsigned<TypeParam>::value ? 37 : -105;
  43. const TypeParam kNegOneOrZero = std::is_unsigned<TypeParam>::value ? 0 : -1;
  44. constexpr int kCount = 1000;
  45. absl::InsecureBitGen gen;
  46. for (const auto& param : {
  47. param_type(),
  48. param_type(2, 2), // Same
  49. param_type(9, 32),
  50. param_type(kMin, 115),
  51. param_type(kNegOneOrZero, Limits::max()),
  52. param_type(Limits::min(), Limits::max()),
  53. param_type(Limits::lowest(), Limits::max()),
  54. param_type(Limits::min() + 1, Limits::max() - 1),
  55. }) {
  56. const auto a = param.a();
  57. const auto b = param.b();
  58. absl::uniform_int_distribution<TypeParam> before(a, b);
  59. EXPECT_EQ(before.a(), param.a());
  60. EXPECT_EQ(before.b(), param.b());
  61. {
  62. // Initialize via param_type
  63. absl::uniform_int_distribution<TypeParam> via_param(param);
  64. EXPECT_EQ(via_param, before);
  65. }
  66. // Initialize via iostreams
  67. std::stringstream ss;
  68. ss << before;
  69. absl::uniform_int_distribution<TypeParam> after(Limits::min() + 3,
  70. Limits::max() - 5);
  71. EXPECT_NE(before.a(), after.a());
  72. EXPECT_NE(before.b(), after.b());
  73. EXPECT_NE(before.param(), after.param());
  74. EXPECT_NE(before, after);
  75. ss >> after;
  76. EXPECT_EQ(before.a(), after.a());
  77. EXPECT_EQ(before.b(), after.b());
  78. EXPECT_EQ(before.param(), after.param());
  79. EXPECT_EQ(before, after);
  80. // Smoke test.
  81. auto sample_min = after.max();
  82. auto sample_max = after.min();
  83. for (int i = 0; i < kCount; i++) {
  84. auto sample = after(gen);
  85. EXPECT_GE(sample, after.min());
  86. EXPECT_LE(sample, after.max());
  87. if (sample > sample_max) {
  88. sample_max = sample;
  89. }
  90. if (sample < sample_min) {
  91. sample_min = sample;
  92. }
  93. }
  94. std::string msg = absl::StrCat("Range: ", +sample_min, ", ", +sample_max);
  95. ABSL_RAW_LOG(INFO, "%s", msg.c_str());
  96. }
  97. }
  98. TYPED_TEST(UniformIntDistributionTest, ViolatesPreconditionsDeathTest) {
  99. #if GTEST_HAS_DEATH_TEST
  100. // Hi < Lo
  101. EXPECT_DEBUG_DEATH({ absl::uniform_int_distribution<TypeParam> dist(10, 1); },
  102. "");
  103. #endif // GTEST_HAS_DEATH_TEST
  104. #if defined(NDEBUG)
  105. // opt-mode, for invalid parameters, will generate a garbage value,
  106. // but should not enter an infinite loop.
  107. absl::InsecureBitGen gen;
  108. absl::uniform_int_distribution<TypeParam> dist(10, 1);
  109. auto x = dist(gen);
  110. // Any value will generate a non-empty string.
  111. EXPECT_FALSE(absl::StrCat(+x).empty()) << x;
  112. #endif // NDEBUG
  113. }
  114. TYPED_TEST(UniformIntDistributionTest, TestMoments) {
  115. constexpr int kSize = 100000;
  116. using Limits = std::numeric_limits<TypeParam>;
  117. using param_type =
  118. typename absl::uniform_int_distribution<TypeParam>::param_type;
  119. // We use a fixed bit generator for distribution accuracy tests. This allows
  120. // these tests to be deterministic, while still testing the qualify of the
  121. // implementation.
  122. absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};
  123. std::vector<double> values(kSize);
  124. for (const auto& param :
  125. {param_type(0, Limits::max()), param_type(13, 127)}) {
  126. absl::uniform_int_distribution<TypeParam> dist(param);
  127. for (int i = 0; i < kSize; i++) {
  128. const auto sample = dist(rng);
  129. ASSERT_LE(dist.param().a(), sample);
  130. ASSERT_GE(dist.param().b(), sample);
  131. values[i] = sample;
  132. }
  133. auto moments = absl::random_internal::ComputeDistributionMoments(values);
  134. const double a = dist.param().a();
  135. const double b = dist.param().b();
  136. const double n = (b - a + 1);
  137. const double mean = (a + b) / 2;
  138. const double var = ((b - a + 1) * (b - a + 1) - 1) / 12;
  139. const double kurtosis = 3 - 6 * (n * n + 1) / (5 * (n * n - 1));
  140. // TODO(ahh): this is not the right bound
  141. // empirically validated with --runs_per_test=10000.
  142. EXPECT_NEAR(mean, moments.mean, 0.01 * var);
  143. EXPECT_NEAR(var, moments.variance, 0.015 * var);
  144. EXPECT_NEAR(0.0, moments.skewness, 0.025);
  145. EXPECT_NEAR(kurtosis, moments.kurtosis, 0.02 * kurtosis);
  146. }
  147. }
  148. TYPED_TEST(UniformIntDistributionTest, ChiSquaredTest50) {
  149. using absl::random_internal::kChiSquared;
  150. constexpr size_t kTrials = 1000;
  151. constexpr int kBuckets = 50; // inclusive, so actally +1
  152. constexpr double kExpected =
  153. static_cast<double>(kTrials) / static_cast<double>(kBuckets);
  154. // Empirically validated with --runs_per_test=10000.
  155. const int kThreshold =
  156. absl::random_internal::ChiSquareValue(kBuckets, 0.999999);
  157. const TypeParam min = std::is_unsigned<TypeParam>::value ? 37 : -37;
  158. const TypeParam max = min + kBuckets;
  159. // We use a fixed bit generator for distribution accuracy tests. This allows
  160. // these tests to be deterministic, while still testing the qualify of the
  161. // implementation.
  162. absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};
  163. absl::uniform_int_distribution<TypeParam> dist(min, max);
  164. std::vector<int32_t> counts(kBuckets + 1, 0);
  165. for (size_t i = 0; i < kTrials; i++) {
  166. auto x = dist(rng);
  167. counts[x - min]++;
  168. }
  169. double chi_square = absl::random_internal::ChiSquareWithExpected(
  170. std::begin(counts), std::end(counts), kExpected);
  171. if (chi_square > kThreshold) {
  172. double p_value =
  173. absl::random_internal::ChiSquarePValue(chi_square, kBuckets);
  174. // Chi-squared test failed. Output does not appear to be uniform.
  175. std::string msg;
  176. for (const auto& a : counts) {
  177. absl::StrAppend(&msg, a, "\n");
  178. }
  179. absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n");
  180. absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ",
  181. kThreshold);
  182. ABSL_RAW_LOG(INFO, "%s", msg.c_str());
  183. FAIL() << msg;
  184. }
  185. }
  186. TEST(UniformIntDistributionTest, StabilityTest) {
  187. // absl::uniform_int_distribution stability relies only on integer operations.
  188. absl::random_internal::sequence_urbg urbg(
  189. {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
  190. 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
  191. 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
  192. 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
  193. std::vector<int> output(12);
  194. {
  195. absl::uniform_int_distribution<int32_t> dist(0, 4);
  196. for (auto& v : output) {
  197. v = dist(urbg);
  198. }
  199. }
  200. EXPECT_EQ(12, urbg.invocations());
  201. EXPECT_THAT(output, testing::ElementsAre(4, 4, 3, 2, 1, 0, 1, 4, 3, 1, 3, 1));
  202. {
  203. urbg.reset();
  204. absl::uniform_int_distribution<int32_t> dist(0, 100);
  205. for (auto& v : output) {
  206. v = dist(urbg);
  207. }
  208. }
  209. EXPECT_EQ(12, urbg.invocations());
  210. EXPECT_THAT(output, testing::ElementsAre(97, 86, 75, 41, 36, 16, 38, 92, 67,
  211. 30, 80, 38));
  212. {
  213. urbg.reset();
  214. absl::uniform_int_distribution<int32_t> dist(0, 10000);
  215. for (auto& v : output) {
  216. v = dist(urbg);
  217. }
  218. }
  219. EXPECT_EQ(12, urbg.invocations());
  220. EXPECT_THAT(output, testing::ElementsAre(9648, 8562, 7439, 4089, 3571, 1602,
  221. 3813, 9195, 6641, 2986, 7956, 3765));
  222. }
  223. } // namespace