uniform_real_distribution_test.cc 13 KB

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