-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandom.cpp
64 lines (55 loc) · 1.23 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
#include "random.h"
static short bsr (int val) {
short res = -1;
while (val) {
val >>= 1;
++res;
}
return res;
}
void initialize(){
srand(time(NULL));
rand();
}
uint64_t random(uint8_t bitlen){
bitlen = bitlen > sizeof(uint64_t) * 8? sizeof(uint64_t) * 8 : bitlen;
uint64_t r = 0;
for (int i = 0; i < bitlen; i += 15){
r <<= 15;
r ^= rand();
}
return bitlen == sizeof(uint64_t) * 8? r : r % ((uint64_t)1 << bitlen);
}
uint64_t random(int64_t min, int64_t max){
int bitlen = bsr(max - min);
uint64_t r;
do {
r = 0;
for (int i = 0; i < bitlen; i += 15) {
r <<= 15;
r ^= rand();
}
} while (r > (max - min));
return r + min;
}
double udrv(){ //uniformly destributed random variable
return random(64) / (double((uint64_t)1 << 32)) / ((uint64_t)1 << 32); //[0, 1)
return random(64) / (double)((uint64_t)-1); //[0, 1]
}
double gauss(double M = 0., double dev = 1.){ //normal distribution
float u, e;
do {
u = udrv();
e = -log(udrv());
} while(u >= exp(-(e-1)*(e-1)));
return ( coin()? u : -u ) * dev + M;
}
bool coin(uint8_t pos){
return (random() >> (pos%63)) % 2;
}
bool coin(){
return rand() % 2;
}
bool generator(double p, double(*f)(void) = udrv){
return (f() < p);
}