Index: base/rand_util_unittest.cc |
diff --git a/base/rand_util_unittest.cc b/base/rand_util_unittest.cc |
index d7fa37af827e8589299c4a066ef83308ca4a384a..80a65b108144007817f2f86b117ee0c134a888ce 100644 |
--- a/base/rand_util_unittest.cc |
+++ b/base/rand_util_unittest.cc |
@@ -61,3 +61,41 @@ TEST(RandUtilTest, RandGeneratorForRandomShuffle) { |
EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(), |
std::numeric_limits<int64>::max()); |
} |
+ |
+TEST(RandUtilTest, RandGeneratorIsUniform) { |
+ // Verify that RandGenerator has a uniform distribution. This is a |
+ // regression test that consistently failed when RandGenerator was |
+ // implemented this way: |
+ // |
+ // return base::RandUint64() % max; |
+ // |
+ // The worst case for such an implementation is e.g. a top of range |
+ // that is 2/3rds of the way to MAX_UINT64, in which case the bottom |
jar (doing other things)
2011/05/28 17:26:40
You got me to wondering about this ratio, and it w
|
+ // half of the range would be twice as likely to occur as the top |
+ // half, assuming a naive modulus implementation of RandGenerator. |
+ const uint64 kTopOfRange = (std::numeric_limits<uint64>::max() / 3L) * 2L; |
+ const uint64 kExpectedAverage = kTopOfRange / 2L; |
+ const uint64 kAllowedVariance = kExpectedAverage / 50L; // +/- 2% |
+ const int kMinAttempts = 1000; |
+ const int kMaxAttempts = 1000000; |
+ |
+ double cumulative_average = 0.0; |
+ int count = 0; |
+ while (count < kMaxAttempts) { |
+ uint64 value = base::RandGenerator(kTopOfRange); |
+ cumulative_average = (count * cumulative_average + value) / (count + 1); |
+ |
+ // Don't quit too quickly for things to start converging, or we may have |
+ // a false positive. |
+ if (count > kMinAttempts && |
+ kExpectedAverage - kAllowedVariance < cumulative_average && |
+ cumulative_average < kExpectedAverage + kAllowedVariance) { |
+ break; |
+ } |
+ |
+ ++count; |
+ } |
+ |
+ ASSERT_LT(count, kMaxAttempts) << "Expected average was " << |
+ kExpectedAverage << ", average ended at " << cumulative_average; |
+} |