redis lua腳本學習筆記math.random()獲取隨機數

原文:redis lua腳本學習筆記math.random()獲取隨機數


最近在公司研究lua在redis中的使用,其中有個算法要使用到隨機數,但運行lua的math.random()後一直返回同一個數字,萬能的stackoverflow也沒能得到答案,最後通過一個很magic的方式實現的。

代碼如下:

function rnd(max)
  --lua的第1次random數不靠譜,取第3次的靠譜
  local ret=0
  math.randomseed(os.time())
  for i=1,3 do
    n = math.random(max)
    ret=n
  end
  return ret
end

print(rnd(10))

每次運行的結果都不同

10

9

8

基本能滿足需求了,雖然會稍微損耗些cpu。

另外的解決思路是通過client端生成隨機數來調用,比如java的Random類。

另附上lua的math函數庫

函數名 描述 示例 結果
pi 圓周率 math.pi 3.1415926535898
abs 取絕對值 math.abs(-2012) 2012
ceil 向上取整 math.ceil(9.1) 10
floor 向下取整 math.floor(9.9) 9
max 取參數最大值 math.max(2,4,6,8) 8
min 取參數最小值 math.min(2,4,6,8) 2
pow 計算x的y次冪 math.pow(2,16) 65536
sqrt 開平方 math.sqrt(65536) 256
mod 取模 math.mod(65535,2) 1
modf 取整數和小數部分 math.modf(20.12) 20   0.12
randomseed 設隨機數種子 math.randomseed(os.time())  
random 取隨機數 math.random(5,90) 5~90
rad 角度轉弧度 math.rad(180) 3.1415926535898
deg 弧度轉角度 math.deg(math.pi) 180
exp e的x次方 math.exp(4) 54.598150033144
log 計算x的自然對數 math.log(54.598150033144) 4
log10 計算10爲底,x的對數 math.log10(1000) 3
frexp 將參數拆成x * (2 ^ y)的形式 math.frexp(160) 0.625    8
ldexp 計算x * (2 ^ y) math.ldexp(0.625,8) 160
sin 正弦 math.sin(math.rad(30)) 0.5
cos 餘弦 math.cos(math.rad(60)) 0.5
tan 正切 math.tan(math.rad(45)) 1
asin 反正弦 math.deg(math.asin(0.5)) 30
acos 反餘弦 math.deg(math.acos(0.5)) 60
atan 反正切 math.deg(math.atan(1)) 45
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章