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