Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(3286)

Unified Diff: base/rand_util.cc

Issue 7080005: Fix base::RandGenerator bug (it had non-uniform random distribution). (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Switch to bitwise operations. Max to 1000. Created 9 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | base/rand_util_unittest.cc » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: base/rand_util.cc
diff --git a/base/rand_util.cc b/base/rand_util.cc
index 4140e9a539867026e856f50e670118378f2512ea..e556c07e8e7d90aedeb1555c39244d0aeffcff5e 100644
--- a/base/rand_util.cc
+++ b/base/rand_util.cc
@@ -45,7 +45,20 @@ double BitsToOpenEndedUnitInterval(uint64 bits) {
uint64 RandGenerator(uint64 max) {
DCHECK_GT(max, 0ULL);
- return base::RandUint64() % max;
+
+ // We must discard random results above this number, as they would
+ // make the random generator non-uniform (consider e.g. if
+ // MAX_UINT64 was 4 and max was 3, then a result of 1 would be twice
+ // as likely as a result of 0 or 2).
+ uint64 max_acceptable_value =
+ (std::numeric_limits<uint64>::max() / max) * max;
+
+ uint64 value;
+ do {
+ value = base::RandUint64();
+ } while (value >= max_acceptable_value);
+
+ return value % max;
}
void RandBytes(void* output, size_t output_length) {
« no previous file with comments | « no previous file | base/rand_util_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698