-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathsimul.h
More file actions
44 lines (32 loc) · 784 Bytes
/
simul.h
File metadata and controls
44 lines (32 loc) · 784 Bytes
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
#ifndef SIMUL_H_
#define SIMUL_H_
#include <cassert>
#include <random>
#include "boost_compat.h"
class simul {
public:
simul(unsigned int seed) : engine(seed) {
}
// interval : [,)
// random number should be in [0, arr[len - 1])
// If by chance arr[len - 1] == 0.0, one possibility is to sample uniformly from 0 ... len - 1
int sample(double* arr, int len) {
int l, r, mid;
double prb = random() * arr[len - 1];
l = 0; r = len - 1;
while (l <= r) {
mid = (l + r) / 2;
if (arr[mid] <= prb) l = mid + 1;
else r = mid - 1;
}
if (l >= len) {
assert(arr[len - 1] == 0.0);
l = int(random() * len);
}
return l;
}
double random() { return boost_uniform_01(engine); }
private:
std::mt19937 engine;
};
#endif /* SIMUL_H_ */