37 static pthread_mutex_t THR_LOCK_mt;
38 static pthread_mutex_t THR_LOCK_gaussian;
39 static bool mt_initialized =
false;
41 static unsigned long mt_buffer[
MT_LEN];
42 static double nextGaussian;
43 static bool haveNextGaussian =
false;
46 pthread_mutex_destroy(&THR_LOCK_gaussian);
47 pthread_mutex_destroy(&THR_LOCK_mt);
48 mt_initialized =
false;
56 pthread_mutex_init(&THR_LOCK_mt, NULL);
57 pthread_mutex_init(&THR_LOCK_gaussian, NULL);
58 pthread_mutex_lock(&THR_LOCK_mt);
59 mt_initialized =
true;
60 srand((
unsigned int) time(NULL));
61 for (i = 0; i <
MT_LEN; i++) {
62 mt_buffer[i] = (
unsigned long) rand() << 16;
63 mt_buffer[i] += (
unsigned long) rand() & 0xFFFF;
66 pthread_mutex_unlock(&THR_LOCK_mt);
75 pthread_mutex_lock(&THR_LOCK_mt);
80 for (; i <
MT_IB; i++) {
81 s =
TWIST(mt_buffer, i, i+1);
82 mt_buffer[i] = mt_buffer[i +
MT_IA] ^ (s >> 1) ^
MAGIC(s);
84 for (; i <
MT_LEN-1; i++) {
85 s =
TWIST(mt_buffer, i, i+1);
86 mt_buffer[i] = mt_buffer[i -
MT_IB] ^ (s >> 1) ^
MAGIC(s);
89 s =
TWIST(mt_buffer, MT_LEN-1, 0);
90 mt_buffer[MT_LEN-1] = mt_buffer[
MT_IA-1] ^ (s >> 1) ^
MAGIC(s);
93 r = mt_buffer[mt_index];
94 pthread_mutex_unlock(&THR_LOCK_mt);
98 r ^= (r << 7) & 0x9D2C5680;
99 r ^= (r << 15) & 0xEFC60000;
106 ((((
unsigned long long)
random() & 0x00000000FFFFFFC0L) << 21)
107 ^ ((
unsigned long long)
random() >> 5))
108 / (double) 0x0020000000000000L;
112 double a1, a2, q, ret;
113 pthread_mutex_lock(&THR_LOCK_gaussian);
114 if (haveNextGaussian) {
115 haveNextGaussian =
false;
121 q = a1 * a1 + a2 * a2;
122 }
while ( q <= 0 || q > 1 );
123 q = sqrt(-2 * log(q) / q );
124 nextGaussian = a1 * q;
125 haveNextGaussian =
true;
128 pthread_mutex_unlock(&THR_LOCK_gaussian);
static void deinit()
Deinitialize the class.
Definitions needed for using threads and mutexes.
#define TWIST(b, i, j)
merge bit 31 of one parameter with the low bits of the other parameter.
Definitions for random number generations.
static double nextDouble()
Returns random double number.
#define MAGIC(s)
distribute the low bit
#define MT_LEN
length of buffer
static double gaussian()
Returns variate of the normal distribution.
static void init()
Initialize the class.
#define MT_IB
length - offset in buffer
#define MT_IA
offset in buffer
static unsigned long random()
Returns random integer number.