diff options
Diffstat (limited to 'src/stable')
-rw-r--r-- | src/stable/randommersenne.cpp | 44 | ||||
-rw-r--r-- | src/stable/randommersenne.h | 31 |
2 files changed, 75 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 | |||
diff --git a/src/stable/randommersenne.h b/src/stable/randommersenne.h new file mode 100644 index 0000000..27c100e --- /dev/null +++ b/src/stable/randommersenne.h | |||
@@ -0,0 +1,31 @@ | |||
1 | #ifndef BU_RANDOM_MERSENNE_H | ||
2 | #define BU_RANDOM_MERSENNE_H | ||
3 | |||
4 | #include "bu/randombase.h" | ||
5 | |||
6 | namespace Bu | ||
7 | { | ||
8 | /** | ||
9 | * An implementation of Mersenne Twister (MT19937) algorithm. This as an | ||
10 | * algorithm with an excellent reputation for very good random number | ||
11 | * generation and a very large period. It is however, relatively slow and | ||
12 | * complex compared to, say the Complementary Multiply With Carry | ||
13 | * (Bu::RandomCmwc), and may not actually be a *better* random number | ||
14 | * generator. | ||
15 | */ | ||
16 | class RandomMersenne : public Bu::RandomBase | ||
17 | { | ||
18 | public: | ||
19 | RandomMersenne( int32_t iSeed=0 ); | ||
20 | virtual ~RandomMersenne(); | ||
21 | |||
22 | virtual void seed( int32_t iSeed ); | ||
23 | virtual int32_t rand(); | ||
24 | |||
25 | private: | ||
26 | int32_t iIndex; | ||
27 | uint32_t iMt[624]; | ||
28 | }; | ||
29 | }; | ||
30 | |||
31 | #endif | ||