【问题标题】:Lua 5.2.1 - Random NumbersLua 5.2.1 - 随机数
【发布时间】:2014-01-01 04:38:19
【问题描述】:

在 Lua 5.2.1 中,我尝试用

生成一个随机数
num = math.random(9)

但是,每次我运行我的程序时:

num = math.random(9)
print("The generated number is "..num..".")

我得到了相同的号码。

brendan@osiris:~$ lua number 
The generated number is 8.
brendan@osiris:~$ lua number 
The generated number is 8.
brendan@osiris:~$ lua number 
The generated number is 8.

这很令人沮丧,因为每次我尝试生成一个新数字并重新启动程序时,都会得到相同的序列。

有不同的生成数字的方法吗?

另外,我也调查过

math.randomseed(os.time())

但我真的不明白。如果这确实是解决方案,您能否解释一下它是如何工作的、它的作用以及我会得到什么数字?

谢谢,

  • 布伦丹

【问题讨论】:

标签: random lua numbers


【解决方案1】:

这并不是 Lua 特有的。伪随机生成器通常是这样工作的:它们需要一个 seed 来启动,并且它们生成的序列并不是真正随机的,而是在给定种子的情况下实际上是确定性的。这对于调试来说是件好事,但对于生产来说,您需要以“随机”的方式更改种子。一种简单而典型的方法是在程序开始时使用时间设置种子一次

【讨论】:

    【解决方案2】:

    在 Lua 中,这是预期的输出。不能保证您在不同的会话中获得不同的序列。

    但是,随后对math.random 的任何调用都会生成一个新号码:

    >> lua
    > =math.random(9)
    1
    
    >> lua
    > =math.random(9)
    1
    
    >> lua
    > =math.random(9)
    1
    > =math.random(9)
    6
    > =math.random(9)
    2
    

    math.randomseed() 将更改重播的序列。例如,如果您设置math.randomseed(3),您将始终得到相同的序列,就像上面一样:

    >> lua
    > math.randomseed(3)
    > =math.random(9)
    1
    > =math.random(9)
    2
    > =math.random(9)
    3
    
    >> lua
    > math.randomseed(3)
    > =math.random(9)
    1
    > =math.random(9)
    2
    > =math.random(9)
    3
    

    如果您在每次运行时将math.randomseed() 设置为唯一值,例如 os.time(),那么您当然每次都会获得唯一的序列。

    【讨论】:

      【解决方案3】:

      首先,你必须调用'math.randomseed()'

      “为什么?”

      因为 Lua 会生成伪随机数。

      --'math.randomseed()' 的最佳种子之一就是时间。

      所以,你首先要写:

      math.randomseed(os.time())
      

      之后,

      num = math.random(9)
      print("The generated number is "..num..".")
      

      但是,Windows 上存在一个错误。那么如果你只写'num = math.random(9)',我认为生成的数字将在 1 小时内保持不变。

      '那么我该如何解决这个问题呢?'

      很简单,你需要做一个for循环。

      for n = 0, 5 do
          num = math.random(9)
      end
      

      因此,在 Windows 中,最终代码为:

      math.randomseed(os.time())
      
      for n = 0, 5 do
          num = math.random(9)
      end
      
      print("The generated number is "..num..".")
      

      OBS:如果 'for n = 0, 5 do' 不能完美运行,则将 5 替换为 10。

      【讨论】:

        猜你喜欢
        • 2014-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-07
        • 1970-01-01
        • 2012-09-21
        • 2013-03-23
        • 1970-01-01
        相关资源
        最近更新 更多