为什么在lua中的某些平台上第一个随机数总是相同? [英] Why is the first random number always the same on some platforms in lua?

查看:133
本文介绍了为什么在lua中的某些平台上第一个随机数总是相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下lua代码段:

Consider the following lua code snippet :

local time = os.time()
for _= 1, 10 do
    time = time + 1
    print('Seeding with ' .. time)
    math.randomseed(time)
    for i = 1, 5 do
        print('\t' .. math.random(100))
    end
end

在Linux机器上,结果是预期的随机数.但似乎至少在Mac OS X上,更改种子后的第一个随机数始终是相同的!

On a Linux machine, the result is, as expected, random numbers. But it seems that at least on Mac OS X, the first random number after changing the seed is always the same !

我想这与Lua依靠C rand()函数生成随机数有关,但是有人有解释吗?

I guess this is related to the fact that Lua relies on the C rand() function for generating random numbers, but does anybody have an explanation ?

这是Linux机器上上述代码输出的摘录(即,输出符合预期):

here is an extract of the output of the above code on a linux machine (ie the output is as expected) :

$ lua test.lua
Seeding with 1232472273
    69
    30
    83
    59
    84
Seeding with 1232472274
    5
    21
    63
    91
    27
[...]

在OS X机器上,与...一起播种"之后的第一个数字始终为66.

On an OS X machine, the first number after "Seeding with ..." was always 66.

推荐答案

Lua随机用于使用C的rand(3)srand(3)函数(在可用的情况下使用random(3)

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.

C90标准和POSIX都建议randsrand的跨平台实现不是最好的.它的低位尤其缺乏随机性.

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.

一些平台,例如Linux,从标准建议中移出了更好的实现方式(例如 random(3 )).

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

OS/X仍然遵循经典的rand实现,而Lua继承了它.

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

这篇关于为什么在lua中的某些平台上第一个随机数总是相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆