2013-04-22 198 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