| OLD | NEW |
| (Empty) |
| 1 /* | |
| 2 * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. | |
| 3 * | |
| 4 * Use of this source code is governed by a BSD-style license | |
| 5 * that can be found in the LICENSE file in the root of the source | |
| 6 * tree. An additional intellectual property rights grant can be found | |
| 7 * in the file PATENTS. All contributing project authors may | |
| 8 * be found in the AUTHORS file in the root of the source tree. | |
| 9 */ | |
| 10 | |
| 11 #include "webrtc/test/random.h" | |
| 12 | |
| 13 #include <math.h> | |
| 14 | |
| 15 #include "webrtc/base/checks.h" | |
| 16 | |
| 17 namespace webrtc { | |
| 18 | |
| 19 namespace test { | |
| 20 | |
| 21 Random::Random(uint32_t seed) : a_(0x531FDB97 ^ seed), b_(0x6420ECA8 + seed) { | |
| 22 } | |
| 23 | |
| 24 uint32_t Random::Rand(uint32_t t) { | |
| 25 // If b / 2^32 is uniform on [0,1), then b / 2^32 * (t+1) is uniform on | |
| 26 // the interval [0,t+1), so the integer part is uniform on [0,t]. | |
| 27 uint64_t result = b_ * (static_cast<uint64_t>(t) + 1); | |
| 28 result >>= 32; | |
| 29 a_ ^= b_; | |
| 30 b_ += a_; | |
| 31 return result; | |
| 32 } | |
| 33 | |
| 34 uint32_t Random::Rand(uint32_t low, uint32_t high) { | |
| 35 RTC_DCHECK(low <= high); | |
| 36 return Rand(high - low) + low; | |
| 37 } | |
| 38 | |
| 39 template <> | |
| 40 float Random::Rand<float>() { | |
| 41 const double kScale = 1.0f / (static_cast<uint64_t>(1) << 32); | |
| 42 double result = kScale * b_; | |
| 43 a_ ^= b_; | |
| 44 b_ += a_; | |
| 45 return static_cast<float>(result); | |
| 46 } | |
| 47 | |
| 48 template <> | |
| 49 bool Random::Rand<bool>() { | |
| 50 return Rand(0, 1) == 1; | |
| 51 } | |
| 52 | |
| 53 int Random::Gaussian(int mean, int standard_deviation) { | |
| 54 // Creating a Normal distribution variable from two independent uniform | |
| 55 // variables based on the Box-Muller transform, which is defined on the | |
| 56 // interval (0, 1], hence the mask+add below. | |
| 57 const double kPi = 3.14159265358979323846; | |
| 58 const double kScale = 1.0 / 0x80000000ul; | |
| 59 double u1 = kScale * ((a_ & 0x7ffffffful) + 1); | |
| 60 double u2 = kScale * ((b_ & 0x7ffffffful) + 1); | |
| 61 a_ ^= b_; | |
| 62 b_ += a_; | |
| 63 return static_cast<int>( | |
| 64 mean + standard_deviation * sqrt(-2 * log(u1)) * cos(2 * kPi * u2)); | |
| 65 } | |
| 66 | |
| 67 int Random::Exponential(float lambda) { | |
| 68 float uniform = Rand<float>(); | |
| 69 return static_cast<int>(-log(uniform) / lambda); | |
| 70 } | |
| 71 } // namespace test | |
| 72 } // namespace webrtc | |
| OLD | NEW |