Why is the first random number always the same on some platforms in lua?

前端 未结 5 1029
眼角桃花
眼角桃花 2021-01-18 15:50

Consider the following lua code snippet :

local time = os.time()
for _= 1, 10 do
    time = time + 1
    print(\'Seeding with \' .. time)
    math.randomseed         


        
相关标签:
5条回答
  • 2021-01-18 16:12

    Check these links out.

    http://lua-users.org/lists/lua-l/2007-03/msg00564.html

    http://lua-users.org/lists/lua-l/2007-03/msg00572.html

    0 讨论(0)
  • 2021-01-18 16:21

    As others noted, Lua intentionally uses C90 random generator for portability sake -- and C90 RNG is not very good.

    If you need good random numbers, use some Lua module to get it. For example, here is Mersenne Twister RNG binding by one of Lua authors.

    0 讨论(0)
  • 2021-01-18 16:25

    If you use the same seed, you will get the same string of numbers from the C rand() function, but you should get a different string of numbers each time since you appear to be using the current time as the seed.

    Edit: I suppose I should elaborate on my answer. If you are not getting a random string of numbers when seeding with os.time(), you may not be getting what you expect from that function call. What are the values you are getting back from os.time()?

    Edit #2: Also, what is the output from that block of code?

    0 讨论(0)
  • 2021-01-18 16:35

    Lua's random used to use C's rand(3) and srand(3) functions (see here). UPDATE: newer Lua versions use random(3) where available.

    Both the C90 standard and POSIX suggest an cross-platform implementation of rand and srand that isn't the best. It especially lacks randomness in the lower bits.

    Some platforms like Linux moved off of the standard recommendation to a better implementation (e.g. random(3)).

    OS/X remains true to the classic rand implementation, and Lua inherits it.

    0 讨论(0)
  • 2021-01-18 16:36

    It's generally a bad idea to call srand multiple times with seeds that are numerically close (and especially bad to do so with time values). In many cases, the variance of the first random number is similar to the variance of the seeds. When dealing with a scripting language that has to convert number representations, it can be even more so.

    Does the same thing occur if you change your seed value by a larger amount?

    0 讨论(0)
提交回复
热议问题