-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrandom.cpp
67 lines (56 loc) · 1.91 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
66
67
#include "random.hpp"
#include <cassert>
#include <random>
#include <cstdint>
#include <algorithm>
#include <iostream>
#include <functional>
#include <limits>
#include <sstream>
our_random_engine& rand_engine(){
static our_random_engine e[PRNG_THREAD_MAX];
return e[omp_get_thread_num()];
}
//Be sure to read: http://www.pcg-random.org/posts/cpp-seeding-surprises.html
//and http://www.pcg-random.org/posts/cpps-random_device.html
void seed_rand(unsigned long seed){
#pragma omp parallel //All threads must come here
{
#pragma omp critical //But only one at a time
{
if(seed==0){
std::uint_least32_t seed_data[std::mt19937::state_size];
std::random_device r;
std::generate_n(seed_data, std::mt19937::state_size, std::ref(r));
std::seed_seq q(std::begin(seed_data), std::end(seed_data));
rand_engine().seed(q);
} else {
rand_engine().seed( seed*static_cast<unsigned int>(omp_get_thread_num()) );
}
}
}
}
int uniform_rand_int(int from, int thru){
static std::uniform_int_distribution<> d[PRNG_THREAD_MAX];
using parm_t = std::uniform_int_distribution<>::param_type;
return d[omp_get_thread_num()]( rand_engine(), parm_t{from, thru} );
}
double uniform_rand_real(double from, double thru){
static std::uniform_real_distribution<> d[PRNG_THREAD_MAX];
using parm_t = std::uniform_real_distribution<>::param_type;
return d[omp_get_thread_num()]( rand_engine(), parm_t{from, thru} );
}
double normal_rand(double mean, double stddev){
static std::normal_distribution<double> d[PRNG_THREAD_MAX];
using parm_t = std::normal_distribution<double>::param_type;
return d[omp_get_thread_num()]( rand_engine(), parm_t{mean, stddev} );
}
RandomEngineState SaveRandomState(){
std::ostringstream oss;
oss<<rand_engine();
return oss.str();
}
void SetRandomState(const RandomEngineState &res){
std::istringstream iss(res);
iss>>rand_engine();
}