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> | 9 #include <limits> |
10 | 10 |
11 #include "base/basictypes.h" | 11 #include "base/basictypes.h" |
12 #include "base/logging.h" | 12 #include "base/logging.h" |
13 | 13 |
14 namespace base { | 14 namespace base { |
15 | 15 |
16 int RandInt(int min, int max) { | 16 int RandInt(int min, int max) { |
17 DCHECK(min <= max); | 17 DCHECK(min <= max); |
18 | 18 |
19 uint64 range = static_cast<int64>(max) - min + 1; | 19 uint64 range = static_cast<int64>(max) - min + 1; |
20 uint64 number = base::RandUInt64(); | 20 uint64 number = base::RandUint64(); |
21 int result = min + static_cast<int>(number % range); | 21 int result = min + static_cast<int>(number % range); |
22 DCHECK(result >= min && result <= max); | 22 DCHECK(result >= min && result <= max); |
23 return result; | 23 return result; |
24 } | 24 } |
25 | 25 |
26 double RandDouble() { | 26 double RandDouble() { |
27 // We try to get maximum precision by masking out as many bits as will fit | 27 // We try to get maximum precision by masking out as many bits as will fit |
28 // in the target type's mantissa, and raising it to an appropriate power to | 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 | 29 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa |
30 // is expected to accommodate 53 bits. | 30 // is expected to accommodate 53 bits. |
31 | 31 |
32 COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn); | 32 COMPILE_ASSERT(std::numeric_limits<double>::radix == 2, otherwise_use_scalbn); |
33 static const int kBits = std::numeric_limits<double>::digits; | 33 static const int kBits = std::numeric_limits<double>::digits; |
34 uint64 random_bits = base::RandUInt64() & ((GG_UINT64_C(1) << kBits) - 1); | 34 uint64 random_bits = base::RandUint64() & ((GG_UINT64_C(1) << kBits) - 1); |
35 double result = ldexp(static_cast<double>(random_bits), -1 * kBits); | 35 double result = ldexp(static_cast<double>(random_bits), -1 * kBits); |
36 DCHECK(result >= 0.0 && result < 1.0); | 36 DCHECK(result >= 0.0 && result < 1.0); |
37 return result; | 37 return result; |
38 } | 38 } |
39 | 39 |
40 } // namespace base | 40 } // namespace base |
OLD | NEW |