Medial Code Documentation
Loading...
Searching...
No Matches
MedGlobalRNG.h
1#ifndef __GLOBAL_RNG_H__
2#define __GLOBAL_RNG_H__
3
4#include <random>
5#include <omp.h>
6
7class globalRNG
8{
9public:
10 static std::minstd_rand::result_type rand() { return getInstance()._rng(); };
11 static unsigned int rand30() { return ((getInstance()._rng() << 15) ^ getInstance()._rng()) & 0x4fffffff; };
12 static void srand(std::minstd_rand::result_type val) { getInstance()._rng.seed(val); };
13 static const std::minstd_rand::result_type max() { return getInstance()._rng.max(); };
14 static std::mt19937 &get_engine() { return getInstance().random_gens[omp_get_thread_num()]; };
15
16private:
17 std::minstd_rand _rng;
18 std::vector<std::mt19937> random_gens;
19
20 static globalRNG &getInstance()
21 {
22 static globalRNG instance; // instansiated on first call
23 return instance;
24 }
25
26 globalRNG() : _rng(20150715)
27 {
28 random_gens.resize(omp_get_max_threads());
29 for (size_t i = 0; i < random_gens.size(); ++i)
30 random_gens[i] = std::mt19937(20150715 + i);
31 }; // constructor
32
33 globalRNG(globalRNG const &)
34 {
35 fprintf(stderr, "Error: copying is forbidden for the globalRNG object\n");
36 exit(-1);
37 }; // no copy constructor
38 void operator=(globalRNG const &)
39 {
40 fprintf(stderr, "Error: assignment is forbidden for the globalRNG object\n");
41 exit(-1);
42 }; // no assignment operator
43};
44
45// inline float rand_1();
46// inline int rand_N(int N);
47// inline float rand_range(float from, float to);
48
49// float random number in 0...1
50inline float rand_1() { return (float)globalRNG::rand() / (float)(globalRNG::max() + 1.0); }
51
52// int random number in 0..N-1
53inline int rand_N(int N) { return ((int)((float)N * rand_1() - (float)1e-8)); }
54inline size_t rand_N_i64(size_t N) { return ((size_t)((double)N * rand_1() - (double)1e-20)); }
55
56// float number in from...to range
57inline float rand_range(float from, float to) { return from + rand_1() * (to - from); }
58
59#endif
Definition globalRNG.h:8
header to handle OpenMP compatibility issues