lua

隨機數生成

inline void MTRand::reload()
{
 // Generate N new values in state
 // Made clearer and faster by Matthew Bellew (matthew.bellew@home.com)
 register uint32 *p = state;
 register int i;
 for( i = N - M; i--; ++p )
  *p = twist( p[M], p[0], p[1] );
 for( i = M; --i; ++p )
  *p = twist( p[M-N], p[0], p[1] );
 *p = twist( p[M-N], p[0], state[0] );

 left = N, pNext = state;
}


uint32 randInt( const uint32& n )
{
 // Find which bits are used in n
 // Optimized by Magnus Jonsson (magnus@smartelectronix.com)
 uint32 used = n;
 used |= used >> 1;
 used |= used >> 2;
 used |= used >> 4;
 used |= used >> 8;
 used |= used >> 16;
 
 // Draw numbers until one is found in [0,n]
 uint32 i;
 do
  i = randInt() & used;  // toss unused bits to shorten search
 while( i > n );
 return i;
}

inline MTRand::uint32 MTRand::randInt()
{
 // Pull a 32-bit integer from the generator state
 // Every other access function simply transforms the numbers extracted here
 
 if( left == 0 ) reload();
 --left;
  
 register uint32 s1;
 s1 = *pNext++;
 s1 ^= (s1 >> 11);
 s1 ^= (s1 <<  7) & 0x9d2c5680UL;
 s1 ^= (s1 << 15) & 0xefc60000UL;
 return ( s1 ^ (s1 >> 18) );
}

uint32 urand (uint32 min, uint32 max)
{
  return mtRand.get ().randInt (max - min) + min;
}



///////////////////

static long s_lHoldRand = 19790213L;
void rtRandomSeed(unsigned int seed)
{
    s_lHoldRand = (long)seed;
}

int rtRandom()
{
    return(((s_lHoldRand = s_lHoldRand * 214013L + 2531011L) >> 16) & 0x7fff);
}

posted on 2013-05-21 23:52 chib 阅读(363) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


<2011年3月>
272812345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(1)

随笔档案

牛人录

时政史料

投资管理

源码库

搜索

最新评论

阅读排行榜

评论排行榜