lua随机数种子取随机数

lua需要生成随机数的需求也是很常见的,为了生成看起来更随机的数字,我们需要注意以下几点

  1. 我们也需要给随机数设置随机数种子:math.randomseed(xx)
  2. lua对随机数种子也是有一定要求的:不能太相近
  3. lua中的os.time()是基于秒的,不太满足lua对随机数种子的要求(如果设置随机数种子的频率太高的话)

那怎么做?
把 os.time()返回的数值字串倒过来再取高位7位。 这样,即使 os.time()变化很小,随机数种子也会很大

math.randomseed(tostring(os.time()):reverse():sub(1, 7))

例:

math.randomseed(tostring(os.time()):reverse():sub(1, 7)) –设置时间种子

for i=1, 15 do
print(math.random()) –产生0到1之间的随机数
print(math.random(1,100)) –产生1到100之间的随机数
end 

转自:https://www.cnblogs.com/gggzly/p/5947892.html

猜你喜欢

转载自blog.csdn.net/qq_42047805/article/details/82629351