Lua數學庫
經常需要在科學和工程計算中進行數學運算,可以使用標準的Lua庫數學來實現。 數學庫中可用的函數列表如下表所示 -
編號
庫或方法
描述
1
math.abs(x)
返回x的絕對值。
2
math.acos(x)
返回x的弧餘弦值(以弧度表示)。
3
math.asin(x)
返回x的弧正弦(以弧度表示)。
4
math.atan(x)
返回x的反正切(以弧度表示)。
5
math.atan2(y,x)
返回y / x的反正切(以弧度表示),但使用兩個參數的符號來查找結果的象限(它也正確處理x爲零的情況。)
6
math.ceil(x)
返回大於或等於x的最小整數。
7
math.cos(x)
返回x的餘弦值(假設爲弧度)。
8
math.cosh(x)
返回x的雙曲餘弦值。
9
math.deg(x)
以度爲單位返回角度x(以弧度表示)。
10
math.exp(x)
返回值e的x次冪。
11
math.floor(x)
返回小於或等於x的最大整數。
12
math.fmod(x,y)
返回x除以y的餘數,將商舍入爲零。
13
math.frexp(x)
返回m和e,使得x = m2e,e是整數,m的絕對值在[0.5,1]範圍內(或者當x爲零時爲零)。
14
math.huge
HUGE_VAL值是一個大於或等於任何其他數值的值。
15
math.ldexp(m, e)
返回m2e(e是一個整數)。
16
math.log(x)
返回x的自然對數。
17
math.log10(x)
返回x的以10爲底的對數。
18
math.max(x,...)
返回參數中的最大值。
19
math.min(x,...)
返回參數中的最小值。
20
math.modf(x)
返回兩個數字,x的整數部分和x的小數部分。
21
math.pi
pi的值。
22
math.pow(x,y)
返回x的y方。(也可以使用表達式x ^ y來計算此值。)
23
math.rad(x)
以弧度爲單位返回角度x(以度爲單位)。
24
math.random([m [, n]])
此函數是ANSI C提供的簡單僞隨機生成器函數rand的接口。
25
math.randomseed(x)
將x設置爲僞隨機生成器的「種子」:相等的種子產生相等的數字序列。
26
math.sin(x)
返回x的正弦值(假設爲弧度)。
27
math.sinh(x)
返回x的雙曲正弦值。
28
math.sqrt(x)
返回x的平方根。(也可以使用表達式x ^ 0.5來計算此值。)
29
math.tan(x)
返回x的正切(假設爲弧度)。
30
math.tanh(x)
返回x的雙曲正切值。
三角函數
使用三角函數的簡單示例如下所示-
radianVal = math.rad(math.pi / 2)
io.write(radianVal,"\n")
-- Sin value of 90(math.pi / 2) degrees
io.write(string.format("%.1f ", math.sin(radianVal)),"\n")
-- Cos value of 90(math.pi / 2) degrees
io.write(string.format("%.1f ", math.cos(radianVal)),"\n")
-- Tan value of 90(math.pi / 2) degrees
io.write(string.format("%.1f ", math.tan(radianVal)),"\n")
-- Cosh value of 90(math.pi / 2) degrees
io.write(string.format("%.1f ", math.cosh(radianVal)),"\n")
-- Pi Value in degrees
io.write(math.deg(math.pi),"\n")
當運行上面的程序時,將得到以下輸出 -
0.027415567780804
0.0
1.0
0.0
1.0
180
其他常見的數學函數
使用常見數學函數的簡單示例如下所示-
-- Floor
io.write("Floor of 10.5055 is ", math.floor(10.5055),"\n")
-- Ceil
io.write("Ceil of 10.5055 is ", math.ceil(10.5055),"\n")
-- Square root
io.write("Square root of 16 is ",math.sqrt(16),"\n")
-- Power
io.write("10 power 2 is ",math.pow(10,2),"\n")
io.write("100 power 0.5 is ",math.pow(100,0.5),"\n")
-- Absolute
io.write("Absolute value of -10 is ",math.abs(-10),"\n")
--Random
math.randomseed(os.time())
io.write("Random number between 1 and 100 is ",math.random(),"\n")
--Random between 1 to 100
io.write("Random number between 1 and 100 is ",math.random(1,100),"\n")
--Max
io.write("Maximum in the input array is ",math.max(1,100,101,99,999),"\n")
--Min
io.write("Minimum in the input array is ",math.min(1,100,101,99,999),"\n")
當運行上面的程序時,將得到以下輸出 -
Floor of 10.5055 is 10
Ceil of 10.5055 is 11
Square root of 16 is 4
10 power 2 is 100
100 power 0.5 is 10
Absolute value of -10 is 10
Random number between 1 and 100 is 0.22876674703207
Random number between 1 and 100 is 7
Maximum in the input array is 999
Minimum in the input array is 1
上面的例子只是一些常見的例子,可以根據需要使用數學庫,所以嘗試使用所有的函數以更熟悉運用。