梅森旋转随机数生成实例

梅森旋转演算法Mersenne twister)是一个伪随机数发生算法。由松本真西村拓士[1]在1997年开发,基于有限二进制字段上的矩阵线性递归F_{2}。可以快速产生高质量的伪随机数, 修正了古典随机数发生算法的很多缺陷。

Mersenne Twister这个名字来自周期长度取自梅森素数的这样一个事实。这个算法通常使用两个相近的变体,不同之处在于使用了不同的梅森素数。一个更新的和更常用的是MT19937, 32位字长。 还有一个变种是64位版的MT19937-64。 对于一个k位的长度,Mersenne Twister会在[0,2^k-1]的区间之间生成离散型均匀分布的随机数。

优点:

最为广泛使用Mersenne Twister的一种变体是MT19937,可以产生32位整数序列。具有以下的优点:

  1. 周期非常长,达到219937−1。尽管如此长的周期并不必然意味着高质量的伪随机数,但短周期(比如许多旧版本软件包提供的232)确实会带来许多问题。
  2. 在1 ≤ k ≤ 623的维度之间都可以均等分布(参见定义).
  3. 除了在统计学意义上的不正确的随机数生成器以外,在所有伪随机数生成器法中是最快的(当时)

梅森旋转算法实现:

//************************************************************************
 //  This is a slightly modified version of Equamen mersenne twister.
 //
 //  Copyright (C) 2009 Chipset
 //
 //  This program is free software: you can redistribute it and/or modify
 //  it under the terms of the GNU Affero General Public License as
 //  published by the Free Software Foundation, either version 3 of the
 //  License, or (at your option) any later version.
 //
 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 //  GNU Affero General Public License for more details.
 //
 //  You should have received a copy of the GNU Affero General Public License
 //  along with this program. If not, see <http://www.gnu.org/licenses/>.
 //************************************************************************
 
 // Original Coyright (c) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura
 //
 // Functions for MT19937, with initialization improved 2002/2/10.
 // Coded by Takuji Nishimura and Makoto Matsumoto.
 // This is a faster version by taking Shawn Cokus's optimization,
 // Matthe Bellew's simplification, Isaku Wada's real version.
 // C++ version by Lyell Haynes (Equamen)
 //
 // Redistribution and use in source and binary forms, with or without
 // modification, are permitted provided that the following conditions
 // are met:
 //
 // 1. Redistributions of source code must retain the above copyright
 //    notice, this list of conditions and the following disclaimer.
 //
 // 2. Redistributions in binary form must reproduce the above copyright
 //    notice, this list of conditions and the following disclaimer in the
 //    documentation and/or other materials provided with the distribution.
 //
 // 3. The names of its contributors may not be used to endorse or promote
 //    products derived from this software without specific prior written
 //    permission.
 //
 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 // A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 //
 
 #ifndef mtrandom_HPP_
 #define mtrandom_HPP_
 
 #include <stddef.h>
 
 class mtrandom
 {
 public:
     mtrandom() : left(1) { init(); }
 
     explicit mtrandom(size_t seed) : left(1) {    init(seed);    }
 
     mtrandom(size_t* init_key, int key_length) : left(1)
     {
         int i = 1, j = 0;
         int k = N > key_length ? N : key_length;
         init();
         for(; k; --k)
         {
             state[i]  =  (state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1664525UL))+ init_key[j] + j; // non linear
             state[i] &=  4294967295UL; // for WORDSIZE > 32 machines
             ++i;
             ++j;
             if(i >= N)
             {
                 state[0] = state[N - 1];
                 i = 1;
             }
             if(j >= key_length)
                 j = 0;
         }
 
         for(k = N - 1; k; --k)
         {
             state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1566083941UL)) - i; // non linear
             state[i] &= 4294967295UL; // for WORDSIZE > 32 machines
             ++i;
             if(i >= N)
             {
                 state[0] = state[N - 1];
                 i = 1;
             }
         }
 
         state[0]  =  2147483648UL; // MSB is 1; assuring non-zero initial array
     }
 
     void reset(size_t rs)
     {
         init(rs);
         next_state();
     }
 
     size_t rand()
     {
         size_t y;
         if(0 == --left)
             next_state();
         y  = *next++;
         // Tempering
         y ^= (y >> 11);
         y ^= (y << 7) & 0x9d2c5680UL;
         y ^= (y << 15) & 0xefc60000UL;
         y ^= (y >> 18);
         return y;
     }
 
     double real()    {    return (double)rand() / -1UL;    }
 
         // generates a random number on [0,1) with 53-bit resolution
     double res53()
     {
         size_t a = rand() >> 5, b = rand() >> 6;
         return (a * 67108864.0 + b) / 9007199254740992.0;
     }
 
 private:
     void init(size_t seed = 19650218UL)
     {
         state[0] =  seed & 4294967295UL;
         for(int j = 1; j < N; ++j)
         {
             state[j]  =  (1812433253UL * (state[j - 1] ^ (state[j - 1]  >>  30)) + j);
             // See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
             // In the previous versions, MSBs of the seed affect
             // only MSBs of the array state[].
             // 2002/01/09 modified by Makoto Matsumoto
             state[j] &=  4294967295UL;  // for >32 bit machines
         }
     }
 
     void next_state()
     {
         size_t* p = state;
         int i;
 
         for(i = N - M + 1; --i; ++p)
             *p = (p[M] ^ twist(p[0], p[1]));
 
         for(i = M; --i; ++p)
             *p = (p[M - N] ^ twist(p[0], p[1]));
         *p = p[M - N] ^ twist(p[0], state[0]);
         left = N;
         next = state;
     }
 
     size_t mixbits(size_t u, size_t v) const
     {
         return (u & 2147483648UL) | (v & 2147483647UL);
     }
 
     size_t twist(size_t u, size_t v) const
     {
         return ((mixbits(u, v)  >>  1) ^ (v & 1UL ? 2567483615UL : 0UL));
     }
 
     static const int N = 624, M = 397;
     size_t state[N];
     size_t left;
     size_t* next;
 };
 
 class mtrand_help
 {
   static mtrandom r;
 public:
   mtrand_help() {}
   void operator()(size_t s) { r.reset(s); }
   size_t operator()() const { return r.rand(); }
   double operator()(double) { return r.real(); }
 };
 mtrandom mtrand_help:: r;
 
 extern void mtsrand(size_t s) { mtrand_help()(s); }
 extern size_t mtirand() { return mtrand_help()(); }
 extern double mtdrand() { return mtrand_help()(1.0); }
 
 #endif // mtrandom_HPP_
 

应用举例:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stddef.h>
#include <ctime>
using namespace std;

class mtrandom
{
public:
	mtrandom() : left(1) { init(); }
 
	explicit mtrandom(size_t seed) : left(1) {    init(seed);    }
 
	mtrandom(size_t* init_key, int key_length) : left(1)
	{
		int i = 1, j = 0;
		int k = N > key_length ? N : key_length;
		init();
		for(; k; --k)
		{
			state[i]  =  (state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1664525UL))+ init_key[j] + j; // non linear
			state[i] &=  4294967295UL; // for WORDSIZE > 32 machines
			++i;
			++j;
			if(i >= N)
			{
				state[0] = state[N - 1];
				i = 1;
			}
			if(j >= key_length)
				j = 0;
		}
 
		for(k = N - 1; k; --k)
		{
			state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1566083941UL)) - i; // non linear
			state[i] &= 4294967295UL; // for WORDSIZE > 32 machines
			++i;
			if(i >= N)
			{
				state[0] = state[N - 1];
				i = 1;
			}
		}
 
		state[0]  =  2147483648UL; // MSB is 1; assuring non-zero initial array
	}
 
	void reset(size_t rs)
	{
		init(rs);
		next_state();
	}
 
	size_t rand()
	{
		size_t y;
		if(0 == --left)
			next_state();
		y  = *next++;
		// Tempering
		y ^= (y >> 11);
		y ^= (y << 7) & 0x9d2c5680UL;
		y ^= (y << 15) & 0xefc60000UL;
		y ^= (y >> 18);
		return y;
	}
 
	double real()    {    return (double)rand() / -1UL;    }
 
	// generates a random number on [0,1) with 53-bit resolution
	double res53()
	{
		size_t a = rand() >> 5, b = rand() >> 6;
		return (a * 67108864.0 + b) / 9007199254740992.0;
	}
 
public:
	void init(size_t seed = 19650218UL)
	{
		state[0] =  seed & 4294967295UL;
		for(int j = 1; j < N; ++j)
		{
			state[j]  =  (1812433253UL * (state[j - 1] ^ (state[j - 1]  >>  30)) + j);
			// See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
			// In the previous versions, MSBs of the seed affect
			// only MSBs of the array state[].
			// 2002/01/09 modified by Makoto Matsumoto
			state[j] &=  4294967295UL;  // for >32 bit machines
		}
	}
 
	void next_state()
	{
		size_t* p = state;
		int i;
 
		for(i = N - M + 1; --i; ++p)
			*p = (p[M] ^ twist(p[0], p[1]));
 
		for(i = M; --i; ++p)
			*p = (p[M - N] ^ twist(p[0], p[1]));
		*p = p[M - N] ^ twist(p[0], state[0]);
		left = N;
		next = state;
	}
 
	size_t mixbits(size_t u, size_t v) const
	{
		return (u & 2147483648UL) | (v & 2147483647UL);
	}
 
	size_t twist(size_t u, size_t v) const
	{
		return ((mixbits(u, v)  >>  1) ^ (v & 1UL ? 2567483615UL : 0UL));
	}
 
	static const int N = 624, M = 397;
	size_t state[N];
	size_t left;
	size_t* next;
};
 
class mtrand_help
{
public:
	static mtrandom r;
public:
	mtrand_help() {}
	void operator()(size_t s) { r.reset(s); }
	size_t operator()() const { return r.rand(); }
	double operator()(double) { return r.real(); }
};
mtrandom mtrand_help:: r;
 
void mtsrand(size_t s) { mtrand_help()(s); }
size_t mtirand() { return mtrand_help()(); }
double mtdrand() { return mtrand_help()(1.0); }


int Random(int low, int high);
int Random2(double start, double end);
int Random3(double start, double end);
int main(int argc, char *argv[])
{
    mtsrand(time(NULL));
	int t = mtdrand()*10;//0~1.0
	cout << t << endl;
	for(int i=0;i<100;i++)
	{
		if(i%5 == 0)
			cout << endl;
		cout << Random(1,50)<<" ";
	}
    cout << endl;

    return 0;
}
//[low high]
int Random(int low, int high)  
{  
    return low + mtirand() % (high - low + 1);  
}  
//[start end)
int Random2(double start, double end)  
{  
    return start+(end-start)*rand()/(RAND_MAX + 1.0);  
}






  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
梅森旋转算法是一种常见的伪随机数生成算法,其原理是通过一系列位运算和循环移位操作来生成随机数。下面是一个用C语言实现的梅森旋转随机数生成器: ```c #include <stdint.h> #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL #define UPPER_MASK 0x80000000UL #define LOWER_MASK 0x7fffffffUL static uint32_t mt[N]; static int mti = N + 1; void init_genrand(uint32_t seed) { mt[0] = seed; for (mti = 1; mti < N; mti++) { mt[mti] = 1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti; } } void generate_numbers() { int i; uint32_t y; static uint32_t mag01[2] = {0x0UL, MATRIX_A}; for (i = 0; i < N; i++) { y = (mt[i] & UPPER_MASK) | (mt[(i+1) % N] & LOWER_MASK); mt[i] = mt[(i+M) % N] ^ (y >> 1) ^ mag01[y & 0x1UL]; } mti = 0; } uint32_t extract_number() { if (mti >= N) { generate_numbers(); } uint32_t y = mt[mti++]; y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } ``` 这个实现中,我们使用了一个624个元素的数组 `mt` 来存储当前的状态,用 `mti` 来记录当前状态的位置。在 `init_genrand` 函数中,我们初始化了这个数组,以 `seed` 为种子生成初始状态。然后,在 `generate_numbers` 函数中,我们使用了梅森旋转算法来更新状态数组。最后,在 `extract_number` 函数中,我们根据当前状态生成一个随机数,并更新状态位置。 要使用这个随机数生成器,可以按照以下方式调用: ```c init_genrand(12345); for (int i = 0; i < 10; i++) { uint32_t rand_num = extract_number(); printf("%u\n", rand_num); } ``` 这个例子中,我们以 `12345` 为种子初始化了随机数生成器,并生成了10个随机数

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值