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