-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathRandom.cpp
65 lines (54 loc) · 1.54 KB
/
Random.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <time.h>
#include <limits.h>
#include <thread>
#include "config.h"
#include "Random.h"
#include "Utils.h"
Random* Random::get_Rng(void) {
static thread_local Random s_rng;
return &s_rng;
}
Random::Random(int seed) {
if (seed == -1) {
size_t thread_id =
std::hash<std::thread::id>()(std::this_thread::get_id());
seedrandom((uint32)time(0) ^ (uint32)thread_id);
} else {
seedrandom(seed);
}
}
// This is xoroshiro128+.
// Note that the last bit isn't entirely random, so don't use it,
// if possible.
uint64 Random::random(void) {
const uint64 s0 = m_s[0];
uint64 s1 = m_s[1];
const uint64 result = s0 + s1;
s1 ^= s0;
m_s[0] = Utils::rotl(s0, 55) ^ s1 ^ (s1 << 14);
m_s[1] = Utils::rotl(s1, 36);
return result;
}
uint16 Random::randuint16(const uint16 max) {
return ((random() >> 48) * max) >> 16;
}
uint32 Random::randuint32(const uint32 max) {
return ((random() >> 32) * (uint64)max) >> 32;
}
uint32 Random::randuint32() {
return random() >> 32;
}
void Random::seedrandom(uint32 seed) {
// Magic values from Pierre L’Ecuyer,
// "Tables of Linear Congruental Generators of different sizes and
// good lattice structure"
m_s[0] = (741103597 * seed);
m_s[1] = (741103597 * m_s[0]);
}
float Random::randflt(void) {
// We need a 23 bit mantissa + implicit 1 bit = 24 bit number
// starting from a 64 bit random.
constexpr float umax = 1.0f / (UINT32_C(1) << 24);
uint32 rnd = random() >> 40;
return ((float)rnd) * umax;
}