花生肉泥 Blog

Lua标准库-math库

2016/11/08 Share

lua标准库之数学库

数学库概念

数学库由算术函数的标准集合组成;比如三角函数(sin、cos、tan、asin、acos、etc)
幂指函数(exp、log、log10),舍入函数(floor、ceil)、max、min,加上一个变量pi,数学库也定义了一个幂操作符 ^

函数 描述 示例 结果
abs 取绝对值 math.abs(-15) 15
acos 反余弦函数 math.acos(0.5) 1.04719755
asin 反正弦函数 math.asin(0.5) 0.52359877
atan2 x / y的反正切值 math.atan2(90.0, 45.0) 1.10714871
atan 反正切函数 math.atan(0.5) 0.463647609
ceil 不小于x的最大整数 math.ceil(5.8) 6
cosh 双曲线余弦函数 math.cosh(0.5) 1.276259652
cos 余弦函数 math.cos(0.5) 0.87758256
deg 弧度转角度 math.deg(math.pi) 180
exp 计算以e为底x次方值 math.exp(2) 2.718281828
floor 不大于x的最大整数 math.floor(5.6) 5
fmod (mod) 取模运算 math.mod(14, 5) 4
frexp 把双精度数val分解为数字部分(尾数)和以2为底的指数n,即val=x*2n math.frexp(10.0) 0.625 4
ldexp 计算value * 2的n次方 math.ldexp(10.0, 3) 80 = 10 * (2 ^3)
log10 计算以10为基数的对数 math.log10(100) 2
log 计算一个数字的自然对数 math.log(2.71) 0.9969
max 取得参数中最大值 math.max(2.71, 100, -98, 23) 100
min 取得参数中最小值 math.min(2.71, 100, -98, 23) -98
modf 把数分为整数和小数 math.modf(15.98) 15 98
pow 得到x的y次方 math.pow(2, 5) 32
rad 角度转弧度 math.rad(180) 3.14159265358
random 获取随机数 math.random(1, 100) math.random(100) 获取1-100的随机数
randomseed 设置随机数种子 math.randomseed(os.time()) 在使用math.random函数之前必须使用此函数设置随机数种子
sinh 双曲线正弦函数 math.sinh(0.5) 0.5210953
sin 正弦函数 math.sin(math.rad(30)) 0.5
sqrt 开平方函数 math.sqrt(16) 4
tanh 双曲线正切函数 math.tanh(0.5) 0.46211715
tan 正切函数 math.tan(0.5) 0.5463024

math.random

产生伪随机数,有三种调用方式
第一:不带参数,产生[0,1)范围内的随机数

1
print(math.random())     -- 0.0012512588885159

第二:带一个参数n,将产生1到n内的随机数(包括1和n)

1
print(math.random(80))     -- 45

第三:带两个参数m和n,将产生m到n内的随机数(包含m和n)

1
print(math.random(1,80))     -- 16

math.randomseed

random的伪随机原理:在程序开始时,他是使用固定的种子初始化随机数发生器,使得每次运行都会拥有相同的关卡
解决方法,使用系统时间作为种子,通常放在脚本最开始的位置math.randomseed(os.time())

1
2
3
4
math.randomseed(os.time())
for i = 1,5 do
print(math.random(1,10))
end

math.abs

math.abs(X) 返回X的绝对值,通常在时间戳的计算上使用率最高

1
2
3
4
5
local n = os.time()
for k = 1,10000000000 do
end
local new = os.time()
print(math.abs(new-n)) -- 30(单位秒)

math.floor

math.floor(X) 函数返回不大于参数X的最大整数

1
2
print(math.floor(5.2))     -- 5
print(math.floor(-5.2)) -- -6

math.ceil

math.ceil(X) 函数返回不小于参数X的最大整数

1
2
print(math.ceil(5.2))     -- 6
print(math.ceil(-5.2)) -- -5

math.sqrt

math.sqrt(X) 返回参数X的平方根或1/2方根 如果X为负,产生域错误

1
print(maht.sqrt(16))     -- 4

math.fmod

math.fmod(X,Y) 返回参数X/Y的余数

1
print(math.fmod(55,50))     --5

math.modf

math.modf(X) 将参数X分割为整数和小数,返回两个值

1
print(math.modf(5.3))     --5 0.3

math.max

math.max(X…)函数返回所有参数最大值

1
print(math.max(1,2,3,4,5))     -- 5

math.mim

math.min(X…)函数返回所有参数的最小值

1
print(math.min(1,2,3,4,5))     -- 1

CATALOG
  1. 1. 数学库概念
  2. 2. math.random
  3. 3. math.randomseed
  4. 4. math.abs
  5. 5. math.floor
  6. 6. math.ceil
  7. 7. math.sqrt
  8. 8. math.fmod
  9. 9. math.modf
  10. 10. math.max
  11. 11. math.mim