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) 返回值ex次幂。
11 math.floor(x) 返回小于或等于x的最大整数。
12 math.fmod(x,y) 返回x除以y的余数,将商舍入为零。
13 math.frexp(x) 返回me,使得x = m2ee是整数,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) 返回xy方。(也可以使用表达式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

上面的例子只是一些常见的例子,可以根据需要使用数学库,所以尝试使用所有的函数以更熟悉运用。


上一篇:Lua标准库

下一篇:Lua操作系统工具

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程