diff options
author | Mike Buland <eichlan@xagasoft.com> | 2012-11-09 19:10:54 +0000 |
---|---|---|
committer | Mike Buland <eichlan@xagasoft.com> | 2012-11-09 19:10:54 +0000 |
commit | 21df391dc6055884e621181cbc3b51d9ec2b095c (patch) | |
tree | d92f3423c0585459fdfc0755ae415f0832d478b3 /src/stable/randommersenne.cpp | |
parent | 21e13f0b2c5242a2ee84b404a96d456e5b753056 (diff) | |
download | libbu++-21df391dc6055884e621181cbc3b51d9ec2b095c.tar.gz libbu++-21df391dc6055884e621181cbc3b51d9ec2b095c.tar.bz2 libbu++-21df391dc6055884e621181cbc3b51d9ec2b095c.tar.xz libbu++-21df391dc6055884e621181cbc3b51d9ec2b095c.zip |
Added Mersenne Twister random number generator.
Diffstat (limited to 'src/stable/randommersenne.cpp')
-rw-r--r-- | src/stable/randommersenne.cpp | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/stable/randommersenne.cpp b/src/stable/randommersenne.cpp new file mode 100644 index 0000000..2d9e85b --- /dev/null +++ b/src/stable/randommersenne.cpp | |||
@@ -0,0 +1,44 @@ | |||
1 | #include "bu/randommersenne.h" | ||
2 | |||
3 | Bu::RandomMersenne::RandomMersenne( int32_t iSeed ) : | ||
4 | iIndex( 0 ) | ||
5 | { | ||
6 | seed( iSeed ); | ||
7 | } | ||
8 | |||
9 | Bu::RandomMersenne::~RandomMersenne() | ||
10 | { | ||
11 | } | ||
12 | |||
13 | void Bu::RandomMersenne::seed( int32_t iSeed ) | ||
14 | { | ||
15 | iMt[0] = iSeed; | ||
16 | for( int j = 1; j < 624; j++ ) | ||
17 | { | ||
18 | iMt[j] = 0x6c078965 * (iMt[j-1]^(iMt[j-1]>>30)) + j; | ||
19 | } | ||
20 | } | ||
21 | |||
22 | int32_t Bu::RandomMersenne::rand() | ||
23 | { | ||
24 | if( iIndex == 0 ) | ||
25 | { | ||
26 | for( int j = 0; j < 624; j++ ) | ||
27 | { | ||
28 | uint32_t y = (iMt[j] & 0x80000000) + (iMt[(j+1)%624] & 0x7fffffff); | ||
29 | iMt[j] = iMt[(j+397)%624] ^ (y>>1); | ||
30 | if( (y%2) ) | ||
31 | iMt[j] = iMt[j]^0x9908b0df; | ||
32 | } | ||
33 | } | ||
34 | |||
35 | uint32_t y = iMt[iIndex]; | ||
36 | y = y ^ (y>>11); | ||
37 | y = y ^ ((y<<7)&0x9d2c5680); | ||
38 | y = y ^ ((y<<15)&0xefc60000); | ||
39 | y = y ^ (y>>18); | ||
40 | |||
41 | iIndex = (iIndex + 1) % 624; | ||
42 | return y; | ||
43 | } | ||
44 | |||