-5

我正在尝试(作为一个笨拙的菜鸟)使用这个算法来生成随机数

/* 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肯定更好。

4

1 回答 1

0

编辑:对问题的原始假设完全错误。你得到全零的原因state是没有播种。你需要填充state一些“随机”的东西。

此代码有效。请注意,该功能seed()在科学上绝对没有被证明是好的 - 事实上,我只是边走边编,试图让尽可能多的“位”在种子中尽可能多地变化。您应该对“播种随机数”进行一些研究。(我也试过用 just 播种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;
}
于 2013-04-22T09:11:21.980 回答