lua 生成隨機數總結


lua 5.3文檔中對math.random()的說明

math.random ([m [, n]])

當不帶參數調用時, 返回一個 [0,1) 區間內一致分布的浮點偽隨機數。 當以兩個整數 m 與 n 調用時, math.random 返回一個 [m, n] 區間 內一致分布的整數偽隨機數。 (值 m-n 不能是負數,且必須在 Lua 整數的表示范圍內。) 調用 math.random(n) 等價於 math.random(1,n)

這個函數是對 C 提供的位隨機數函數的封裝。 對其統計屬性不作擔保。    

通過上面的說名,我們知道 math.random()是偽隨機。

如果用原生lua解釋器,需要生成隨機數,我們通常需要種隨機種子,例如:

math.randomseed(os.time())
-- 為了使隨機種的變化范圍大,還可以用
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 9)))
-- 或者的你的應用在1秒鍾內有很多次請求,還可以
ngx.update_time() -- 更新nginx時間
math.randomseed(tonumber(tostring(ngx.now()*1000):reverse():sub(1, 9))) -- 毫秒
 

OpenResty用的是luajit解釋器,luajit的擴展中重新實現了math.random()

LuaJIT uses a Tausworthe PRNG with period 2^223 to implement math.random() and math.randomseed(). The quality of the PRNG results is much superior compared to the standard Lua implementation which uses the platform-specific ANSI rand(). 

詳細參考:http://luajit.org/extensions.html

 

經過測試在使用luajit時,直接使用math.random(),和使用 math.randomseed(tonumber(tostring(ngx.now()*1000):reverse():sub(1, 9))) 都能得到比較理想的隨機數


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM