随机生成数字

Random generation of numbers?

本文关键字:数字 随机      更新时间:2023-10-16

我正在尝试(作为一个笨手笨脚的新手)使用此算法生成随机数

/* initialize state to random bits */
static unsigned long state[16];
/* init should also reset this to 0 */
static unsigned int index = 0;
/* return 32 bit random number */
unsigned long WELLRNG512(void)
{
unsigned long a, b, c, d;
a = state[index];
c = state[(index+13)&15];
b = a^c^(a<<16)^(c<<15);
c = state[(index+9)&15];
c ^= (c>>11);
a = state[index] = b^c;
d = a^((a<<5)&0xDA442D20UL);
index = (index + 15)&15;
a = state[index];
state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
return state[index];
}

但它似乎不工作(结果每次0)。我发现它在这里什么是一个好的随机数生成器的游戏?在评论中有一个人说"我浪费了一个晚上来理解为什么我的代码不能工作:在64位机器上,这段代码生成64位数字!"使用sizeof(unsigned long) * 8"。我有一个64位系统,但我不明白我要做什么!我使用stdlib肯定更好。

编辑:原来对问题的假设完全错误。你得到全0的原因是state没有被播种。你需要用一些'随机'填充state

这段代码可以工作。请注意,seed()函数在科学上绝对没有被证明是好的——事实上,我只是在进行过程中编造了它,试图在种子中获得尽可能多的"比特"。你应该对"播种随机数"做一些研究。(我也试过只用state[i] = i;播种,这似乎也工作得相当好,但你在前几次迭代中得到非常相似的数字)。

#include <iostream>
#include <cstdint>
/* initialize state to random bits */
static uint32_t state[16];
/* init should also reset this to 0 */
static unsigned int index = 0;
/* return 32 bit random number */
uint32_t WELLRNG512(void)
{
    uint32_t a, b, c, d;
    a = state[index];
    c = state[(index+13)&15];
    b = a^c^(a<<16)^(c<<15);
    c = state[(index+9)&15];
    c ^= (c>>11);
    a = state[index] = b^c;
    d = a^((a<<5)&0xDA442D24UL);
    index = (index + 15)&15;
    a = state[index];
    state[index] = a^b^d^(a<<2)^(b<<18)^(c<<28);
    return state[index];
}
void seed()
{
    for(size_t i = 0; i < sizeof(state)/sizeof(state[0]); i++)
    {
    state[i] = (i << (24 + (i & 5))) ^ (i << 7) ^ (i << 6) ^ (i >> 2);
    }
}    
int main()
{
    using namespace std;
    seed();
    for(int i = 0; i < 50; i++)
    {
    cout << WELLRNG512() << endl;
    }
    return 0;
}