Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright (c) 2008 The Chromium Authors. All rights reserved. | |
| 2 // Use of this source code is governed by a BSD-style license that can be | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #include "base/rand_util.h" | |
| 6 | |
| 7 #include <math.h> | |
| 8 | |
| 9 #include "base/basictypes.h" | |
| 10 #include "base/logging.h" | |
| 11 | |
| 12 namespace { | |
| 13 | |
| 14 union uint64_splitter { | |
| 15 uint64 normal; | |
| 16 uint16 split[4]; | |
| 17 }; | |
| 18 | |
| 19 } // namespace | |
| 20 | |
| 21 namespace base { | |
| 22 | |
| 23 int RandInt(int min, int max) { | |
| 24 DCHECK(min <= max); | |
| 25 | |
| 26 uint64 range = static_cast<int64>(max) - min + 1; | |
| 27 uint64 number = base::RandUInt64(); | |
| 28 int result = min + number % range; | |
|
Mark Mentovai
2008/09/29 22:20:05
This needed to be static_cast<int>(number % range)
| |
| 29 DCHECK(result >= min && result <= max); | |
| 30 return result; | |
| 31 } | |
| 32 | |
| 33 double RandDouble() { | |
| 34 uint64_splitter number; | |
| 35 number.normal = base::RandUInt64(); | |
| 36 | |
| 37 // Standard code based on drand48 would give only 48 bits of precision. | |
| 38 // We try to get maximum precision for IEEE 754 double (52 bits). | |
| 39 double result = ldexp(number.split[0] & 0xf, -52) + | |
|
Mark Mentovai
2008/09/29 22:20:05
MSVC is strict about these too, because its C libr
| |
| 40 ldexp(number.split[1], -48) + | |
| 41 ldexp(number.split[2], -32) + | |
| 42 ldexp(number.split[3], -16); | |
| 43 DCHECK(result >= 0.0 && result < 1.0); | |
| 44 return result; | |
| 45 } | |
| 46 | |
| 47 } // namespace base | |
| OLD | NEW |