2013-07-22 78 views
4

我正在研究隨機數字的代碼。我把math.randomseed(os.time())放在一個循環中。代碼如下:隨機種子在LUA

for i = 1, 1000 do 
    math.randomseed(os.time()) 
    j = math.random(i, row-one) 
    u[i], u[j] = u[j], u[i] 
    for k = 1, 11 do 
    file:write(input2[u[i]][k], " ") 
    end 
    file:write"\n" 
end 

而當我運行它幾次,整個輸出總是相同的。隨機種子是不是應該在重新運行時防止重複?

+1

'os.time()'第二期間返回的值相同。 –

+0

@EgorSkriptunoff所以當我重新運行代碼時,如何讓整個結果不同? – Rachelle

+3

不要在一秒內運行相同的代碼兩次:-) –

回答

12

致電math.randomseed一旦在程序的開始。沒有一點在循環中調用它。

2

通常第一個隨機值不是真正的隨機值(但它永遠不會是真正的隨機值,它是一個僞隨機數發生器)。 首先設置一個隨機種子,然後隨機生成它幾次。 試試這個代碼,例如:

math.randomseed(os.time()) 
math.random() math.random() math.random() 
for i = 1, 1000 do 
    j = math.random(i, row-one) 
    u[i], u[j] = u[j], u[i] 
    for k = 1, 11 do 
    file:write(input2[u[i]][k], " ") 
    end 
    file:write"\n" 
end 

但是,你可以從http://lua-users.org/wiki/MathLibraryTutorial試試這個:

-- improving the built-in pseudorandom generator 
do 
    local oldrandom = math.random 
    local randomtable 
    math.random = function() 
     if randomtable == nil then 
     randomtable = {} 
     for i = 1, 97 do 
      randomtable[i] = oldrandom() 
     end 
     end 
     local x = oldrandom() 
     local i = 1 + math.floor(97*x) 
     x, randomtable[i] = randomtable[i], x 
     return x 
    end 
end