forked from btgraham/SparseConvNet-archived
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRng.cpp
More file actions
63 lines (60 loc) · 1.57 KB
/
Rng.cpp
File metadata and controls
63 lines (60 loc) · 1.57 KB
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
#define RNG_CPP
#include "Rng.h"
#include <iostream>
#include <algorithm>
#include <chrono>
#include <time.h>
#include <sys/time.h>
#include <mach/clock.h>
#include <mach/mach.h>
RNG::RNG() : stdNormal(0,1), uniform01(0,1) {
timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service( mach_host_self(), CALENDAR_CLOCK, &cclock );
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
RNGseedGeneratorMutex.lock();
gen.seed(RNGseedGenerator()+ts.tv_nsec);
RNGseedGeneratorMutex.unlock();
}
int RNG::randint(int n) {
if (n==0) return 0;
else return gen()%n;
}
float RNG::uniform(float a, float b) {
return a+(b-a)*uniform01(gen);
}
float RNG::normal(float mean, float sd) {
return mean+sd*stdNormal(gen);
}
int RNG::bernoulli(float p) {
if (uniform01(gen)<p)
return 1;
else
return 0;
}
template <typename T>
int RNG::index(std::vector<T> &v) {
if (v.size()==0) std::cout << "RNG::index called for empty std::vector!\n";
return gen()%v.size();
}
std::vector<int> RNG::NchooseM(int n, int m) {
std::vector<int> ret(m,100);
int ctr=m;
for(int i=0;i<n;i++)
if (uniform01(gen)<ctr*1.0/(n-i)) ret[m-ctr--]=i;
return ret;
}
std::vector<int> RNG::permutation(int n) {
std::vector<int> ret;
for (int i=0;i<n;i++) ret.push_back(i);
std::shuffle ( ret.begin(), ret.end(), gen);
return ret;
}
template <typename T> void RNG::vectorShuffle(std::vector<T> &v) {
std::shuffle( v.begin(), v.end(), gen);
}
template void RNG::vectorShuffle<int>(std::vector<int> &v);