OpenResty實戰-Lua入門-數學庫

OpenResty實戰-Lua入門-數學庫

Lua 數學庫由一組標準的數學函數構成。數學庫的引入豐富了 Lua 編程語言的功能,同時也方便了程序的編寫。常用數學函數見下表:

函數名 函數功能

math.rad(x) 角度x轉換成弧度

math.deg(x) 弧度x轉換成角度

math.max(x, ...) 返回參數中值最大的那個數,參數必須是number型

math.min(x, ...) 返回參數中值最小的那個數,參數必須是number型

math.random ([m[, n]]) 不傳入參數時,返回 一個在區間[0,1)內均勻分佈的偽隨機實數;只使用一個整數參數m時,返回一個在區間[1, m]內均勻分佈的偽隨機整數;使用兩個整數參數時,返回一個在區間[m, n]內均勻分佈的偽隨機整數

math.randomseed(x) 為偽隨機數生成器設置一個種子x,相同的種子將會生成相同的數字序列

math.abs(x) 返回x的絕對值

math.fmod(x, y) 返回 x對y取餘數

math.pow(x, y) 返回x的y次方

math.sqrt(x) 返回x的算術平方根

math.exp(x) 返回自然數e的x次方

math.log(x) 返回x的自然對數

math.log10(x) 返回以10為底,x的對數

math.floor(x) 返回最大且不大於x的整數

math.ceil(x) 返回最小且不小於x的整數

math.pi 圓周率

math.sin(x) 求弧度x的正弦值

math.cos(x) 求弧度x的餘弦值

math.tan(x) 求弧度x的正切值

math.asin(x) 求x的反正弦值

math.acos(x) 求x的反餘弦值

math.atan(x) 求x的反正切值

示例代碼:

print(math.pi) -->output 3.1415926535898

print(math.rad(180)) -->output 3.1415926535898

print(math.deg(math.pi)) -->output 180

print(math.sin(1)) -->output 0.8414709848079

print(math.cos(math.pi)) -->output -1

print(math.tan(math.pi / 4)) -->output 1

print(math.atan(1)) -->output 0.78539816339745

print(math.asin(0)) -->output 0

print(math.max(-1, 2, 0, 3.6, 9.1)) -->output 9.1

print(math.min(-1, 2, 0, 3.6, 9.1)) -->output -1

print(math.fmod(10.1, 3)) -->output 1.1

print(math.sqrt(360)) -->output 18.97366596101

print(math.exp(1)) -->output 2.718281828459

print(math.log(10)) -->output 2.302585092994

print(math.log10(10)) -->output 1

print(math.floor(3.1415)) -->output 3

print(math.ceil(7.998)) -->output 8

另外使用 math.random() 函數獲得偽隨機數時,如果不使用 math.randomseed() 設置偽隨機數生成種子或者設置相同的偽隨機數生成種子,那麼得得到的偽隨機數序列是一樣的。

示例代碼:

math.randomseed (100) --把種子設置為100

print(math.random()) -->output 0.0012512588885159

print(math.random(100)) -->output 57

print(math.random(100, 360)) -->output 150

稍等片刻,再次運行上面的代碼。

math.randomseed (100) --把種子設置為100

print(math.random()) -->output 0.0012512588885159

print(math.random(100)) -->output 57

print(math.random(100, 360)) -->output 150

兩次運行的結果一樣。為了避免每次程序啟動時得到的都是相同的偽隨機數序列,通常是使用當前時間作為種子。

修改上例中的代碼:

math.randomseed (os.time()) --把100換成os.time()

print(math.random()) -->output 0.88369396038697

print(math.random(100)) -->output 66

print(math.random(100, 360)) -->output 228

稍等片刻,再次運行上面的代碼。

math.randomseed (os.time()) --把100換成os.time()

print(math.random()) -->output 0.88946195867794

print(math.random(100)) -->output 68

print(math.random(100, 360)) -->output 12

至此,Lua數學庫就介紹完了,下一篇將介紹Lua的文件操作。

後續計劃內容:

Lua入門+高階

Nginx

OpenResty

LuaRestyRedisLibrary

LuaCjsonLibrary

PostgresNginxModule

LuaNginxModule

LuaRestyDNSLibrary

LuaRestyLock

stream_lua_module

balancer_by_lua

OpenResty 與 SSL

測試

Web服務

火焰圖

OpenResty周邊

零碎知識點


分享到:


相關文章: