OLD | NEW |
1 // Copyright (c) 2008 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "base/rand_util.h" | 5 #include "base/rand_util.h" |
6 | 6 |
7 #include <math.h> | 7 #include <math.h> |
8 | 8 |
| 9 #include <limits> |
| 10 |
9 #include "base/basictypes.h" | 11 #include "base/basictypes.h" |
10 #include "base/logging.h" | 12 #include "base/logging.h" |
11 | 13 |
12 namespace { | |
13 | |
14 union uint64_splitter { | |
15 uint64 normal; | |
16 uint16 split[4]; | |
17 }; | |
18 | |
19 } // namespace | |
20 | |
21 namespace base { | 14 namespace base { |
22 | 15 |
23 int RandInt(int min, int max) { | 16 int RandInt(int min, int max) { |
24 DCHECK(min <= max); | 17 DCHECK(min <= max); |
25 | 18 |
26 uint64 range = static_cast<int64>(max) - min + 1; | 19 uint64 range = static_cast<int64>(max) - min + 1; |
27 uint64 number = base::RandUInt64(); | 20 uint64 number = base::RandUInt64(); |
28 int result = min + static_cast<int>(number % range); | 21 int result = min + static_cast<int>(number % range); |
29 DCHECK(result >= min && result <= max); | 22 DCHECK(result >= min && result <= max); |
30 return result; | 23 return result; |
31 } | 24 } |
32 | 25 |
33 double RandDouble() { | 26 double RandDouble() { |
34 uint64_splitter number; | 27 // We try to get maximum precision by masking out as many bits as will fit |
35 number.normal = base::RandUInt64(); | 28 // in the target type's mantissa, and raising it to an appropriate power to |
| 29 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa |
| 30 // is expected to accommodate 53 bits. |
36 | 31 |
37 // Standard code based on drand48 would give only 48 bits of precision. | 32 COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn); |
38 // We try to get maximum precision for IEEE 754 double (52 bits). | 33 static const int kBits = std::numeric_limits<double>::digits; |
39 double result = ldexp(static_cast<double>(number.split[0] & 0xf), -52) + | 34 uint64 random_bits = base::RandUInt64() & ((GG_UINT64_C(1) << kBits) - 1); |
40 ldexp(static_cast<double>(number.split[1]), -48) + | 35 double result = ldexp(static_cast<double>(random_bits), -1 * kBits); |
41 ldexp(static_cast<double>(number.split[2]), -32) + | |
42 ldexp(static_cast<double>(number.split[3]), -16); | |
43 DCHECK(result >= 0.0 && result < 1.0); | 36 DCHECK(result >= 0.0 && result < 1.0); |
44 return result; | 37 return result; |
45 } | 38 } |
46 | 39 |
47 } // namespace base | 40 } // namespace base |
OLD | NEW |