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_real_distribution.h"
16
17 #include <cfloat>
18 #include <cmath>
19 #include <cstdint>
20 #include <iterator>
21 #include <random>
22 #include <sstream>
23 #include <string>
24 #include <type_traits>
25 #include <vector>
26
27 #include "gmock/gmock.h"
28 #include "gtest/gtest.h"
29 #include "absl/base/internal/raw_logging.h"
30 #include "absl/numeric/internal/representation.h"
31 #include "absl/random/internal/chi_square.h"
32 #include "absl/random/internal/distribution_test_util.h"
33 #include "absl/random/internal/pcg_engine.h"
34 #include "absl/random/internal/sequence_urbg.h"
35 #include "absl/random/random.h"
36 #include "absl/strings/str_cat.h"
37
38 // NOTES:
39 // * Some documentation on generating random real values suggests that
40 // it is possible to use std::nextafter(b, DBL_MAX) to generate a value on
41 // the closed range [a, b]. Unfortunately, that technique is not universally
42 // reliable due to floating point quantization.
43 //
44 // * absl::uniform_real_distribution<float> generates between 2^28 and 2^29
45 // distinct floating point values in the range [0, 1).
46 //
47 // * absl::uniform_real_distribution<float> generates at least 2^23 distinct
48 // floating point values in the range [1, 2). This should be the same as
49 // any other range covered by a single exponent in IEEE 754.
50 //
51 // * absl::uniform_real_distribution<double> generates more than 2^52 distinct
52 // values in the range [0, 1), and should generate at least 2^52 distinct
53 // values in the range of [1, 2).
54 //
55
56 namespace {
57
58 template <typename RealType>
59 class UniformRealDistributionTest : public ::testing::Test {};
60
61 // double-double arithmetic is not supported well by either GCC or Clang; see
62 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99048,
63 // https://bugs.llvm.org/show_bug.cgi?id=49131, and
64 // https://bugs.llvm.org/show_bug.cgi?id=49132. Don't bother running these tests
65 // with double doubles until compiler support is better.
66 using RealTypes =
67 std::conditional<absl::numeric_internal::IsDoubleDouble(),
68 ::testing::Types<float, double>,
69 ::testing::Types<float, double, long double>>::type;
70
71 TYPED_TEST_SUITE(UniformRealDistributionTest, RealTypes);
72
TYPED_TEST(UniformRealDistributionTest,ParamSerializeTest)73 TYPED_TEST(UniformRealDistributionTest, ParamSerializeTest) {
74 #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0
75 // We're using an x87-compatible FPU, and intermediate operations are
76 // performed with 80-bit floats. This produces slightly different results from
77 // what we expect below.
78 GTEST_SKIP()
79 << "Skipping the test because we detected x87 floating-point semantics";
80 #endif
81
82 using param_type =
83 typename absl::uniform_real_distribution<TypeParam>::param_type;
84
85 constexpr const TypeParam a{1152921504606846976};
86
87 constexpr int kCount = 1000;
88 absl::InsecureBitGen gen;
89 for (const auto& param : {
90 param_type(),
91 param_type(TypeParam(2.0), TypeParam(2.0)), // Same
92 param_type(TypeParam(-0.1), TypeParam(0.1)),
93 param_type(TypeParam(0.05), TypeParam(0.12)),
94 param_type(TypeParam(-0.05), TypeParam(0.13)),
95 param_type(TypeParam(-0.05), TypeParam(-0.02)),
96 // double range = 0
97 // 2^60 , 2^60 + 2^6
98 param_type(a, TypeParam(1152921504606847040)),
99 // 2^60 , 2^60 + 2^7
100 param_type(a, TypeParam(1152921504606847104)),
101 // double range = 2^8
102 // 2^60 , 2^60 + 2^8
103 param_type(a, TypeParam(1152921504606847232)),
104 // float range = 0
105 // 2^60 , 2^60 + 2^36
106 param_type(a, TypeParam(1152921573326323712)),
107 // 2^60 , 2^60 + 2^37
108 param_type(a, TypeParam(1152921642045800448)),
109 // float range = 2^38
110 // 2^60 , 2^60 + 2^38
111 param_type(a, TypeParam(1152921779484753920)),
112 // Limits
113 param_type(0, std::numeric_limits<TypeParam>::max()),
114 param_type(std::numeric_limits<TypeParam>::lowest(), 0),
115 param_type(0, std::numeric_limits<TypeParam>::epsilon()),
116 param_type(-std::numeric_limits<TypeParam>::epsilon(),
117 std::numeric_limits<TypeParam>::epsilon()),
118 param_type(std::numeric_limits<TypeParam>::epsilon(),
119 2 * std::numeric_limits<TypeParam>::epsilon()),
120 }) {
121 // Validate parameters.
122 const auto a = param.a();
123 const auto b = param.b();
124 absl::uniform_real_distribution<TypeParam> before(a, b);
125 EXPECT_EQ(before.a(), param.a());
126 EXPECT_EQ(before.b(), param.b());
127
128 {
129 absl::uniform_real_distribution<TypeParam> via_param(param);
130 EXPECT_EQ(via_param, before);
131 }
132
133 std::stringstream ss;
134 ss << before;
135 absl::uniform_real_distribution<TypeParam> after(TypeParam(1.0),
136 TypeParam(3.1));
137
138 EXPECT_NE(before.a(), after.a());
139 EXPECT_NE(before.b(), after.b());
140 EXPECT_NE(before.param(), after.param());
141 EXPECT_NE(before, after);
142
143 ss >> after;
144
145 EXPECT_EQ(before.a(), after.a());
146 EXPECT_EQ(before.b(), after.b());
147 EXPECT_EQ(before.param(), after.param());
148 EXPECT_EQ(before, after);
149
150 // Smoke test.
151 auto sample_min = after.max();
152 auto sample_max = after.min();
153 for (int i = 0; i < kCount; i++) {
154 auto sample = after(gen);
155 // Failure here indicates a bug in uniform_real_distribution::operator(),
156 // or bad parameters--range too large, etc.
157 if (after.min() == after.max()) {
158 EXPECT_EQ(sample, after.min());
159 } else {
160 EXPECT_GE(sample, after.min());
161 EXPECT_LT(sample, after.max());
162 }
163 if (sample > sample_max) {
164 sample_max = sample;
165 }
166 if (sample < sample_min) {
167 sample_min = sample;
168 }
169 }
170
171 if (!std::is_same<TypeParam, long double>::value) {
172 // static_cast<double>(long double) can overflow.
173 std::string msg = absl::StrCat("Range: ", static_cast<double>(sample_min),
174 ", ", static_cast<double>(sample_max));
175 ABSL_RAW_LOG(INFO, "%s", msg.c_str());
176 }
177 }
178 }
179
180 #ifdef _MSC_VER
181 #pragma warning(push)
182 #pragma warning(disable:4756) // Constant arithmetic overflow.
183 #endif
TYPED_TEST(UniformRealDistributionTest,ViolatesPreconditionsDeathTest)184 TYPED_TEST(UniformRealDistributionTest, ViolatesPreconditionsDeathTest) {
185 #if GTEST_HAS_DEATH_TEST
186 // Hi < Lo
187 EXPECT_DEBUG_DEATH(
188 { absl::uniform_real_distribution<TypeParam> dist(10.0, 1.0); }, "");
189
190 // Hi - Lo > numeric_limits<>::max()
191 EXPECT_DEBUG_DEATH(
192 {
193 absl::uniform_real_distribution<TypeParam> dist(
194 std::numeric_limits<TypeParam>::lowest(),
195 std::numeric_limits<TypeParam>::max());
196 },
197 "");
198 #endif // GTEST_HAS_DEATH_TEST
199 #if defined(NDEBUG)
200 // opt-mode, for invalid parameters, will generate a garbage value,
201 // but should not enter an infinite loop.
202 absl::InsecureBitGen gen;
203 {
204 absl::uniform_real_distribution<TypeParam> dist(10.0, 1.0);
205 auto x = dist(gen);
206 EXPECT_FALSE(std::isnan(x)) << x;
207 }
208 {
209 absl::uniform_real_distribution<TypeParam> dist(
210 std::numeric_limits<TypeParam>::lowest(),
211 std::numeric_limits<TypeParam>::max());
212 auto x = dist(gen);
213 // Infinite result.
214 EXPECT_FALSE(std::isfinite(x)) << x;
215 }
216 #endif // NDEBUG
217 }
218 #ifdef _MSC_VER
219 #pragma warning(pop) // warning(disable:4756)
220 #endif
221
TYPED_TEST(UniformRealDistributionTest,TestMoments)222 TYPED_TEST(UniformRealDistributionTest, TestMoments) {
223 constexpr int kSize = 1000000;
224 std::vector<double> values(kSize);
225
226 // We use a fixed bit generator for distribution accuracy tests. This allows
227 // these tests to be deterministic, while still testing the qualify of the
228 // implementation.
229 absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};
230
231 absl::uniform_real_distribution<TypeParam> dist;
232 for (int i = 0; i < kSize; i++) {
233 values[i] = dist(rng);
234 }
235
236 const auto moments =
237 absl::random_internal::ComputeDistributionMoments(values);
238 EXPECT_NEAR(0.5, moments.mean, 0.01);
239 EXPECT_NEAR(1 / 12.0, moments.variance, 0.015);
240 EXPECT_NEAR(0.0, moments.skewness, 0.02);
241 EXPECT_NEAR(9 / 5.0, moments.kurtosis, 0.015);
242 }
243
TYPED_TEST(UniformRealDistributionTest,ChiSquaredTest50)244 TYPED_TEST(UniformRealDistributionTest, ChiSquaredTest50) {
245 using absl::random_internal::kChiSquared;
246 using param_type =
247 typename absl::uniform_real_distribution<TypeParam>::param_type;
248
249 constexpr size_t kTrials = 100000;
250 constexpr int kBuckets = 50;
251 constexpr double kExpected =
252 static_cast<double>(kTrials) / static_cast<double>(kBuckets);
253
254 // 1-in-100000 threshold, but remember, there are about 8 tests
255 // in this file. And the test could fail for other reasons.
256 // Empirically validated with --runs_per_test=10000.
257 const int kThreshold =
258 absl::random_internal::ChiSquareValue(kBuckets - 1, 0.999999);
259
260 // We use a fixed bit generator for distribution accuracy tests. This allows
261 // these tests to be deterministic, while still testing the qualify of the
262 // implementation.
263 absl::random_internal::pcg64_2018_engine rng{0x2B7E151628AED2A6};
264
265 for (const auto& param : {param_type(0, 1), param_type(5, 12),
266 param_type(-5, 13), param_type(-5, -2)}) {
267 const double min_val = param.a();
268 const double max_val = param.b();
269 const double factor = kBuckets / (max_val - min_val);
270
271 std::vector<int32_t> counts(kBuckets, 0);
272 absl::uniform_real_distribution<TypeParam> dist(param);
273 for (size_t i = 0; i < kTrials; i++) {
274 auto x = dist(rng);
275 auto bucket = static_cast<size_t>((x - min_val) * factor);
276 counts[bucket]++;
277 }
278
279 double chi_square = absl::random_internal::ChiSquareWithExpected(
280 std::begin(counts), std::end(counts), kExpected);
281 if (chi_square > kThreshold) {
282 double p_value =
283 absl::random_internal::ChiSquarePValue(chi_square, kBuckets);
284
285 // Chi-squared test failed. Output does not appear to be uniform.
286 std::string msg;
287 for (const auto& a : counts) {
288 absl::StrAppend(&msg, a, "\n");
289 }
290 absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n");
291 absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ",
292 kThreshold);
293 ABSL_RAW_LOG(INFO, "%s", msg.c_str());
294 FAIL() << msg;
295 }
296 }
297 }
298
TYPED_TEST(UniformRealDistributionTest,StabilityTest)299 TYPED_TEST(UniformRealDistributionTest, StabilityTest) {
300 // absl::uniform_real_distribution stability relies only on
301 // random_internal::RandU64ToDouble and random_internal::RandU64ToFloat.
302 absl::random_internal::sequence_urbg urbg(
303 {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
304 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
305 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
306 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
307
308 std::vector<int> output(12);
309
310 absl::uniform_real_distribution<TypeParam> dist;
311 std::generate(std::begin(output), std::end(output), [&] {
312 return static_cast<int>(TypeParam(1000000) * dist(urbg));
313 });
314
315 EXPECT_THAT(
316 output, //
317 testing::ElementsAre(59, 999246, 762494, 395876, 167716, 82545, 925251,
318 77341, 12527, 708791, 834451, 932808));
319 }
320
TEST(UniformRealDistributionTest,AlgorithmBounds)321 TEST(UniformRealDistributionTest, AlgorithmBounds) {
322 absl::uniform_real_distribution<double> dist;
323
324 {
325 // This returns the smallest value >0 from absl::uniform_real_distribution.
326 absl::random_internal::sequence_urbg urbg({0x0000000000000001ull});
327 double a = dist(urbg);
328 EXPECT_EQ(a, 5.42101086242752217004e-20);
329 }
330
331 {
332 // This returns a value very near 0.5 from absl::uniform_real_distribution.
333 absl::random_internal::sequence_urbg urbg({0x7fffffffffffffefull});
334 double a = dist(urbg);
335 EXPECT_EQ(a, 0.499999999999999944489);
336 }
337 {
338 // This returns a value very near 0.5 from absl::uniform_real_distribution.
339 absl::random_internal::sequence_urbg urbg({0x8000000000000000ull});
340 double a = dist(urbg);
341 EXPECT_EQ(a, 0.5);
342 }
343
344 {
345 // This returns the largest value <1 from absl::uniform_real_distribution.
346 absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFEFull});
347 double a = dist(urbg);
348 EXPECT_EQ(a, 0.999999999999999888978);
349 }
350 {
351 // This *ALSO* returns the largest value <1.
352 absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFFFull});
353 double a = dist(urbg);
354 EXPECT_EQ(a, 0.999999999999999888978);
355 }
356 }
357
358 } // namespace
359