2013-04-22 207 views
-5

我想(作为一个笨蛋小白)使用这个alghoritm生成随机数随机生成数字?

/* 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)。我在这里发现它What is a good random number generator for a game?有一个说:“我浪费了一个晚上了解为什么我的代码不工作:在64位机器上,这个代码处理64位数字!使用sizeof(unsigned long) * 8”。我有一个64位系统,但我不明白我必须做什么!我使用stdlib确实更好。

+5

作为一般规则,您绝对不应该使用您自己无法理解的外部来源的代码。它是一种可靠的方式,可以将不可预见的错误添加到您的程序中,即使您复制的摘录正常工作。 – Daboyzuk 2013-04-22 08:44:28

+0

借调,@Daboyzuk。在C++中,如果你运行你不明白的代码,你可以让其他人完全访问你机器的裸机。这会打开你的机器到一个受伤的世界。 – 2013-04-22 08:45:52

+0

我在评论中询问应该使用哪个短语。确保你回头看看是否/当原评论员回复。 – Shahbaz 2013-04-22 08:45:52

回答

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; 
} 
+0

非常感谢你,你真的很友善! – 2013-04-22 09:32:35