michael@0: // Copyright (c) 2008 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/rand_util.h" michael@0: michael@0: #include michael@0: michael@0: #include michael@0: michael@0: #include "base/basictypes.h" michael@0: #include "base/logging.h" michael@0: michael@0: namespace base { michael@0: michael@0: int RandInt(int min, int max) { michael@0: DCHECK(min <= max); michael@0: michael@0: uint64_t range = static_cast(max) - min + 1; michael@0: uint64_t number = base::RandUint64(); michael@0: int result = min + static_cast(number % range); michael@0: DCHECK(result >= min && result <= max); michael@0: return result; michael@0: } michael@0: michael@0: double RandDouble() { michael@0: // We try to get maximum precision by masking out as many bits as will fit michael@0: // in the target type's mantissa, and raising it to an appropriate power to michael@0: // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa michael@0: // is expected to accommodate 53 bits. michael@0: michael@0: COMPILE_ASSERT(std::numeric_limits::radix == 2, otherwise_use_scalbn); michael@0: static const int kBits = std::numeric_limits::digits; michael@0: uint64_t random_bits = base::RandUint64() & ((GG_UINT64_C(1) << kBits) - 1); michael@0: double result = ldexp(static_cast(random_bits), -1 * kBits); michael@0: DCHECK(result >= 0.0 && result < 1.0); michael@0: return result; michael@0: } michael@0: michael@0: } // namespace base