[lua]紫猫lua教程-命令宝典-L1-01-08. math数学函数库

image

L1[math]01. 取绝对值

L1[math]02. 三角函数

小知识:注意 lua下三角函数用的参数是弧度 而不是角度

弧度=角度*pi/180  -->弧度角度换算公式  lua的math库里面也有 弧度和角度转换的2个函数 也可以直接使用   math.rad (x) math.deg (x)

我们要求30度的sin值  那么

print(math.sin(30*math.pi/180))


小知识:知道半径和圆心 如何遍历出圆上的所有点 对于常见的鼠标轨迹 还是有点用处的

圆心坐标(x0,y0) 半径为r

角度为a

圆上任意一点坐标公式

x1=x0+r*cos(a)

y1=y0+r*sin(a)

lua下的取圆上坐标的源码

--圆心坐标
x0=100 y0=100
--半径
r=50
--圆上点初始坐标
x1=0
y1=0
--10度一个间隔输出圆上坐标
for a=0,360,10 do
    x1=x0+r*math.cos(a*math.pi/180)
    y1=y0+r*math.sin(a*math.pi/180)    
    print(a .."°",x1,y1)
end

123


L1[math]03. 取整数

10 //4 =2


L1[math]04. 取余数

print(math.fmod(12,4))


补充知识:以前的table.pack 和table.unpack的用法

table.pack  把参数里面的内容变成1个数字索引表

table.unpack  把参数表的元素一个个返回 相当于return list[i], list[i+1], ···, list[j]

常见用途就是用在了函数的参数 功能和 …类似


小知识:转化为整数 类似按键的isnumeric()函数 检测是否是整数 只要不能转换为整数的返回nil 但是这个是5.3独有的函数

print(math.tointeger("12"))--12
print(math.tointeger(14))—14


自己写了一个判断是否是数值(不是整数)函数

function isnumeric(x)
    local temp=tonumber(x) 
    local result
    --print(temp)
    if (temp) then
        result=true
    else
    result=false
    end 
    return result
end
print(isnumeric(12))
print(isnumeric("12fsdf"))
print(isnumeric("as12fsdf"))
print(isnumeric("12"))


判断是否是整数的小函数

function isint(x)
    local temp=tonumber(x) 
    local result
    --print(temp)
    if (temp) then
        
        --这里判断是数值了 进一步判断是否是整数
        --print(tostring(temp),tostring(math.floor(temp)))
        if (tostring(temp)==tostring(math.floor(temp))) then
            result=true    
        else
            result=false
        end
    else
        result=false
    end 
    return result
end
print(isint("12"))
print(isint("12.54"))
print(isint(12))
print(isint("fds"))

123



L1[math]05. 取随机数


小知识:伪随机的基本原理

种子设置的参数为准  将这个参数带入到math.random()以固定的公式来获取随后的随机

如果种子设置的参数都是3  那么后面得出的随机数都是一样的

x=3
math.randomseed(x)
for i=1,5 do
    print(math.random(-50,50))
end
结果
-28
-22
-22
-29
22
程序于 0.19 秒完成 (pid: 5728).

我们再次运行一次结果依然

-28
-22
-22
-29
22
程序于 0.19 秒完成 (pid: 2740).

结论:为了避免这种伪随机的情况 随机数种子函数的参数必须保持不断的变

解决办法就是 math.randomseed(os.time())  当然这种也是有漏洞的 不过大部分时候都管用

经过测试 每个源码 只需要再开头设置下随机数种子就够了

123

posted @ 2019-07-15 21:43  点-滴  阅读(779)  评论(0编辑  收藏  举报