参考:
常用接口:
abs: 返回指定值的绝对值
print(math.abs(10)) -- 10
print(math.abs(-5)) -- 5
print(math.abs(-1.02)) -- 1.02
cos/sin: 返回指定值的反余弦和正弦值
print(math.acos(0.5)) -- 1.0471975511966
print(math.asin(0.5)) -- 0.5235987755983
acos/asin: 返回指定值的反余弦和正弦值
print(math.acos(0.5)) -- 1.0471975511966
print(math.asin(0.5)) -- 0.5235987755983
cosh/sinh: 返回指定值的双曲线余弦/正弦
print(math.cosh(0.5)) -- 1.1276259652064
print(math.sinh(0.5)) -- 0.52109530549375
atan/atan2: 返回指定值的反正切
print(math.atan2(90, 45)) -- 1.1071487177941
print(math.atan(0.5)) -- 0.46364760900081
deg: 将弧度转角度
print(math.deg(math.pi)) -- 180.0
rad: 将角度转弧度
print(math.rad(180)) -- 3.1415926535898
huge: 与平台相关,最大的数字常量
print(math.huge) -- (Mac)inf
floor/ceil: 向下/上取整
print(math.floor(10.34)) -- 10
print(math.floor(-10.34)) -- -11
print(math.ceil(10.34)) -- 11
print(math.ceil(-10.34)) -- -10
min/max: 返回参数列表下的最小/大值
print(math.min(5)) -- 5
print(math.min(1,5,-7)) -- -7
print(math.max(5)) -- 5
print(math.max(1,5,-7)) -- 5
exp: 返回e(自然对数的底数)为底的乘幂
print(math.exp(2)) -- 7.3890560989307
frexp: 返回双精度val解为尾数和以2为底的指数n,即val=x * 2n
print(math.frexp(10)) -- 0.625 4
Idexp: 返回指定值 * 2的n次方
print(math.ldexp(10, 3)) -- 80.0 即 value = 10 * 2^3
log10: 返回以10为基数的对数
print(math.log10(1000)) -- 3.0
log: 计算一个数字的自然对数
print(math.log(10)) -- 2.302585092994
sqrt: 返回指定值的平方根,注意仅允许非负参数
print(math.sqrt(-100)) -- nan 错误,要是非负整数
print(math.sqrt(25)) -- 5
pow(x,y): 返回x的y次方
print(math.pow(2, 3)) -- 8.0 即 2^3
print(math.pow(5, 2)) -- 25.0 即 5^2
modf: 返回指定值的整型值和小数值
print(math.modf(10.13)) -- 10 0.13
print(math.modf(-5.89)) -- -5 -0.89
random,randomseed: 随机数相关
--[[
random的参数分为如下情况:
1. 不带参数时,生成[0, 1)之间的随机实数
2. 带一个整型参数时,生成[1,n] 之间的随机整数
3. 带两个整型参数时,生成[m,n]之间的随机整数
注意:
1. random的参数必须为整数
2. 使用之前,若未使用randomseed(设置随机种子)生成的随机数是伪随机数
3. 一般情况为避免伪随机,会把种子设置为:os.time() 这样可在一秒种后再调用函数获取新的序列
]]
math.randomseed(os.time())
print(math.random()) -- 0.2959274337627
print(math.random(10)) -- 1
print(math.random(11,99)) -- 57
拓展
-- 来源于cocos2d/function.lua
-- 随机数
function math.newrandomseed()
local ok, socket = pcall(function()
return require("socket")
end)
if ok then
math.randomseed(socket.gettime() * 1000)
else
math.randomseed(os.time())
end
math.random()
math.random()
math.random()
math.random()
end
-- 角度转弧度, 弧度 = 角度 * (π / 180)
local pi_div_180 = math.pi / 180
function math.angle2radian(angle)
return angle * pi_div_180
end
-- 弧度转角度, 角度 = 弧度 * (180 / π)
function math.radian2angle(radian)
return radian * 180 / math.pi
end