lua 生成随机数总结

lua 5.3文档中对math.random()的说明

math.random ([m [, n]])

当不带参数调用时, 返回一个 [0,1) 区间内一致分布的浮点伪随机数。 当以两个整数 m 与 n 调用时, math.random 返回一个 [m, n] 区间 内一致分布的整数伪随机数。 (值 m-n 不能是负数,且必须在 Lua 整数的表示范围内。) 调用 math.random(n) 等价于 math.random(1,n)

这个函数是对 C 提供的位随机数函数的封装。 对其统计属性不作担保。    

通过上面的说名,我们知道 math.random()是伪随机。

如果用原生lua解释器,需要生成随机数,我们通常需要种随机种子,例如:

math.randomseed(os.time())
-- 为了使随机种的变化范围大,还可以用
math.randomseed(tonumber(tostring(os.time()):reverse():sub(1, 9)))
-- 或者的你的应用在1秒钟内有很多次请求,还可以
ngx.update_time() -- 更新nginx时间
math.randomseed(tonumber(tostring(ngx.now()*1000):reverse():sub(1, 9))) -- 毫秒
 

OpenResty用的是luajit解释器,luajit的扩展中重新实现了math.random()

LuaJIT uses a Tausworthe PRNG with period 2^223 to implement math.random() and math.randomseed(). The quality of the PRNG results is much superior compared to the standard Lua implementation which uses the platform-specific ANSI rand(). 

详细参考:http://luajit.org/extensions.html

 

经过测试在使用luajit时,直接使用math.random(),和使用 math.randomseed(tonumber(tostring(ngx.now()*1000):reverse():sub(1, 9))) 都能得到比较理想的随机数

posted @   钻牛角尖儿  阅读(11141)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
点击右上角即可分享
微信分享提示