blob: 89903da8c2098d2e6d790ea3d52cf1756396f70e (
plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
#include "stdafx.h"
#include "Random.h"
#include "System.h"
Random::Random()
{
// 4J - jave now uses the system nanosecond counter added to a "seedUniquifier" to get an initial seed. Our nanosecond timer is actually only millisecond accuate, so
// use QueryPerformanceCounter here instead
int64_t seed;
QueryPerformanceCounter((LARGE_INTEGER *)&seed);
seed += 8682522807148012LL;
setSeed(seed);
}
Random::Random(int64_t seed)
{
setSeed(seed);
}
void Random::setSeed(int64_t s)
{
this->seed = (s ^ 0x5DEECE66DLL) & ((1LL << 48) - 1);
haveNextNextGaussian = false;
}
int Random::next(int bits)
{
seed = (seed * 0x5DEECE66DLL + 0xBLL) & ((1LL << 48) - 1);
return static_cast<int>(seed >> (48 - bits));
}
void Random::nextBytes(byte *bytes, unsigned int count)
{
for(unsigned int i = 0; i < count; i++ )
{
bytes[i] = static_cast<byte>(next(8));
}
}
double Random::nextDouble()
{
return ((static_cast<int64_t>(next(26)) << 27) + next(27))
/ static_cast<double>(1LL << 53);
}
double Random::nextGaussian()
{
if (haveNextNextGaussian)
{
haveNextNextGaussian = false;
return nextNextGaussian;
}
else
{
double v1, v2, s;
do
{
v1 = 2 * nextDouble() - 1; // between -1.0 and 1.0
v2 = 2 * nextDouble() - 1; // between -1.0 and 1.0
s = v1 * v1 + v2 * v2;
} while (s >= 1 || s == 0);
double multiplier = sqrt(-2 * log(s)/s);
nextNextGaussian = v2 * multiplier;
haveNextNextGaussian = true;
return v1 * multiplier;
}
}
int Random::nextInt()
{
return next(32);
}
int Random::nextInt(int n)
{
assert (n>0);
if ((n & -n) == n) // i.e., n is a power of 2
return static_cast<int>((static_cast<int64_t>(next(31)) * n) >> 31); // 4J Stu - Made int64_t instead of long
int bits, val;
do
{
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
float Random::nextFloat()
{
return next(24) / static_cast<float>(1 << 24);
}
int64_t Random::nextLong()
{
return (static_cast<int64_t>(next(32)) << 32) + next(32);
}
bool Random::nextBoolean()
{
return next(1) != 0;
}
|