Random.cpp
Go to the documentation of this file.
1 /*
2  * random.c
3  *
4  * implementiert lagged Fibonacci random sequence
5  * exakt nach Knuth TAOCP Vol.2 pp.186f
6  *
7  */
8 #include <stdio.h>
9 #include "Random.h"
10
11 using namespace MiscLib;
12
13 #define KK 100
14 #define LL 37
15 #define MM MiscLib_RN_RAND_MOD
16 #define TT 70
17
18 #define mod_diff(x,y) ( (x) - (y) & (MM-1) )
19 #define is_odd(x) ( (x) & 1 )
20 #define evenize(x) ( (x) & (MM-2) )
21
24
25 void MiscLib::rn_setseed(size_t seed)
26 {
27  register int t, j;
28  size_t x[KK + KK - 1];
29  register size_t ss = evenize(seed + 2);
30  for (j = 0; j < KK; j++)
31  {
32  x[j] = ss;
33  ss <<= 1;
34  if (ss >= MM)
35  {
36  ss -= MM - 2;
37  }
38  }
39  for (; j < KK + KK - 1; j++)
40  {
41  x[j] = 0;
42  }
43  x[1]++;
44  ss = seed & (MM - 1);
45  t = TT - 1;
46  while (t)
47  {
48  for (j = KK - 1; j > 0; j--)
49  {
50  x[j + j] = x[j];
51  }
52  for (j = KK + KK - 2; j > KK - LL; j -= 2)
53  {
54  x[KK + KK - 1 - j] = evenize(x[j]);
55  }
56  for (j = KK + KK - 2; j >= KK; j--) if (is_odd(x[j]))
57  {
58  x[j - (KK - LL)] = mod_diff(x[j - (KK - LL)], x[j]);
59  x[j - KK] = mod_diff(x[j - KK], x[j]);
60  }
61  if (is_odd(ss))
62  {
63  for (j = KK; j > 0; j--)
64  {
65  x[j] = x[j - 1];
66  }
67  x[0] = x[KK];
68  if (is_odd(x[KK]))
69  {
70  x[LL] = mod_diff(x[LL], x[KK]);
71  }
72  }
73  if (ss)
74  {
75  ss >>= 1;
76  }
77  else
78  {
79  t--;
80  }
81  }
82  for (j = 0; j < LL; j++)
83  {
84  rn_buf[j + KK - LL] = x[j];
85  }
86  for (; j < KK; j++)
87  {
88  rn_buf[j - LL] = x[j];
89  }
90 }
91
93 {
94  /* You remember Duff's device? If it would help then it should be used here */
95  rn_point = 1;
96
97  register int i, j;
98  for (j = KK; j < MiscLib_RN_BUFSIZE; j++)
99  {
100  rn_buf[j] = mod_diff(rn_buf[j - KK], rn_buf[j - LL]);
101  }
102  for (i = 0; i < LL; i++, j++)
103  {
104  rn_buf[i] = mod_diff(rn_buf[j - KK], rn_buf[j - LL]);
105  }
106  for (; i < KK; i++, j++)
107  {
108  rn_buf[i] = mod_diff(rn_buf[j - KK], rn_buf[i - LL]);
109  }
110
111
112  return *rn_buf;
113 }
LL
#define LL
Definition: Random.cpp:14
MiscLib_RN_BUFSIZE
#define MiscLib_RN_BUFSIZE
Definition: Random.h:10
MiscLib::rn_point
size_t rn_point
Definition: Random.cpp:23
KK
#define KK
Definition: Random.cpp:13
TT
#define TT
Definition: Random.cpp:16
MiscLib::rn_setseed
void rn_setseed(size_t)
Definition: Random.cpp:25
is_odd
#define is_odd(x)
Definition: Random.cpp:19
MiscLib
Definition: AlignedAllocator.h:11
MiscLib::rn_buf
size_t rn_buf[]
Definition: Random.cpp:22
MiscLib::rn_refresh
size_t rn_refresh(void)
Definition: Random.cpp:92
Random.h
evenize
#define evenize(x)
Definition: Random.cpp:20
mod_diff
#define mod_diff(x, y)
Definition: Random.cpp:18
MM
#define MM
Definition: Random.cpp:15