梅森旋转产生随机数c语言实现,梅森旋转法产生随机数

直接贴代码了:

#include

#include

typedef unsigned long uint32;

#define N (624) // length of state vector

#define M (397)

#define K (0x9908B0DFU) // a magic constant

#define hiBit(u) ((u) & 0x80000000U) // mask highest bit of u

#define loBit(u) ((u) & 0x00000001U) // mask lowest bit of u

#define loBits(u) ((u) & 0x7FFFFFFFU) // mask all but highest bit of u

#define mixBits(u, v) (hiBit(u) | loBits(v)) // move high bit of u to low bits of v

void seedMT(uint32 seed);

uint32 reloadMT(void);

uint32 randomMT(void);

static uint32 state[N+1];

static uint32 *next;

static int left = -1;

void seedMT(uint32 seed)

{

register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state;

register int j;

for(left = 0, *s++=x, j=N; --j;

*s++ = (x*69069U) & 0xFFFFFFFFFF);

}

uint32 reloadMT(void)

{

register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1;

register int j;

if(left < -1)

seedMT(4357U);

left=N-1, next=state+1;

for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++)

*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);

for(pM=state, j=M; --j; s0=s1, s1=*p2++)

*p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);

s1 = state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);

s1 ^= (s1 >> 11);

s1 ^= (s1 << 7) & 0x9D2C5680U;

s1 ^= (s1 << 15) & 0xEFC60000U;

return (s1 ^ (s1 >> 18));

}

uint32 randomMT(void)

{

uint32 y;

//printf("... left = %d\n", left);

if(--left < 0)

return (reloadMT());

//printf("... *next = %d\n", *next);

y = *next++;

y ^= (y >> 11);

y ^= (y << 7) & 0x9D2C5680U;

y ^= (y << 15) & 0xEFC60000U;

y ^= (y >> 18);

return (y);

}

// test only

int main() {

int seed;

scanf("%d", &seed);

seedMT(seed);

int cnt = 1000000, a = 0, b = 0;

while(cnt--) {

if(randomMT()%2==0) {

a++;

}

else b++;

reloadMT();

}

printf("%d %d\n", a, b);

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值