-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfastrand.c
executable file
·45 lines (35 loc) · 1.24 KB
/
fastrand.c
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
#include "fastrand.h"
static pcg32_random_t pcg32_global = { 0x853c49e6748fea9bULL, 0xda3e39cb94b95bdbULL };
static inline uint32_t pcg32_random_r(pcg32_random_t* rng) {
uint64_t oldstate = rng->state;
rng->state = oldstate * 6364136223846793005ULL + rng->inc;
uint32_t xorshifted = (uint32_t)(((oldstate >> 18u) ^ oldstate) >> 27u);
uint32_t rot = oldstate >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
static inline uint32_t pcg32_random(void) {
return pcg32_random_r(&pcg32_global);
}
void pcg32_init_state(uint32_t state) {
pcg32_global.state = state;
}
static inline void pcg32_init_inc(uint32_t inc) {
pcg32_global.inc = inc | 1;
}
uint32_t pcg32_random_bounded_divisionless(uint32_t range) {
uint64_t random32bit, multiresult;
uint32_t leftover;
uint32_t threshold;
random32bit = pcg32_random();
multiresult = random32bit * range;
leftover = (uint32_t) multiresult;
if(leftover < range ) {
threshold = -range % range ;
while (leftover < threshold) {
random32bit = pcg32_random();
multiresult = random32bit * range;
leftover = (uint32_t) multiresult;
}
}
return multiresult >> 32; // [0, range)
}