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

查看:12
本文介绍了为什么在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('	' .. 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 机器上,Seed with ..."之后的第一个数字总是 66.

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

推荐答案

Lua 的 random 用于使用 C 的 rand(3)srand(3) 函数(见这里).更新:较新的 Lua 版本 在可用的情况下使用 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天全站免登陆