-
Notifications
You must be signed in to change notification settings - Fork 7
/
random.cpp
90 lines (80 loc) · 2.19 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Park/Miller RNG
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "random.h"
#define IA 16807
#define IM 2147483647
#define AM (1.0/IM)
#define IQ 127773
#define IR 2836
#define IA1 1366
#define IC1 150889
#define IM1 714025
#define IA2 8121
#define IC2 28411
#define IM2 134456
#define IA3 7141
#define IC3 54773
#define IM3 259200
/* -----------------------------------------------------------------------------
* initialize
* -------------------------------------------------------------------------- */
RanPark::RanPark(int seed_init)
{
if (seed_init <= 0){printf("\nInvalid seed for Park random # generator\n"); exit(1);}
seed = seed_init;
save = 0;
}
/* -----------------------------------------------------------------------------
* uniform RN
* -------------------------------------------------------------------------- */
double RanPark::uniform()
{
int k = seed/IQ;
seed = IA*(seed-k*IQ) - IR*k;
if (seed < 0) seed += IM;
double ans = AM*seed;
return ans;
}
/* -----------------------------------------------------------------------------
* gaussian RN
* -------------------------------------------------------------------------- */
double RanPark::gaussian()
{
double first,v1,v2,rsq,fac;
if (!save) {
int again = 1;
while (again) {
v1 = 2.0*uniform()-1.0;
v2 = 2.0*uniform()-1.0;
rsq = v1*v1 + v2*v2;
if (rsq < 1.0 && rsq != 0.0) again = 0;
}
fac = sqrt(-2.0*log(rsq)/rsq);
second = v1*fac;
first = v2*fac;
save = 1;
} else {
first = second;
save = 0;
}
return first;
}
/* -----------------------------------------------------------------------------
* reset seed
* -------------------------------------------------------------------------- */
void RanPark::reset(int seed_init)
{
if (seed_init <= 0){printf("\nInvalid seed for Park random # generator\n"); exit(2);}
seed = seed_init;
save = 0;
}
/* -----------------------------------------------------------------------------
* return seed
* -------------------------------------------------------------------------- */
int RanPark::state()
{
return seed;
}
/* -------------------------------------------------------------------------- */