数学库
Lua 数学库由一组标准的数学函数构成。数学库的引入丰富了 Lua 编程语言的功能,同时也方便了程序的编写。常用数学函数见下表:


示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| print(math.pi) print(math.rad(180)) print(math.deg(math.pi))
print(math.sin(1)) print(math.cos(math.pi)) print(math.tan(math.pi / 4))
print(math.atan(1)) print(math.asin(0))
print(math.max(-1, 2, 0, 3.6, 9.1)) print(math.min(-1, 2, 0, 3.6, 9.1))
print(math.fmod(10.1, 3)) print(math.sqrt(360))
print(math.exp(1)) print(math.log(10)) print(math.log10(10))
print(math.floor(3.1415)) print(math.ceil(7.998))
|
另外使用 math.random()
函数获得伪随机数时,如果不使用 math.randomseed()
设置伪随机数生成种子或者设置相同的伪随机数生成种子,那么得得到的伪随机数序列是一样的。
示例代码:
1 2 3 4
| math.randomseed (100) print(math.random()) print(math.random(100)) print(math.random(100, 360))
|
稍等片刻,再次运行上面的代码。
1 2 3 4
| math.randomseed (100) print(math.random()) print(math.random(100)) print(math.random(100, 360))
|
两次运行的结果一样。为了避免每次程序启动时得到的都是相同的伪随机数序列,通常是使用当前时间作为种子。
修改上例中的代码:
1 2 3 4 5
| math.randomseed (os.time()) print(math.random()) print(math.random(100)) print(math.random(100, 360))
|
稍等片刻,再次运行上面的代码。
1 2 3 4
| math.randomseed (os.time()) print(math.random()) print(math.random(100)) print(math.random(100, 360))
|