lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


A few comments:

1) /dev/random on Linux may wait for more entropy if it runs out. Use /dev/urandom for most purposes.

2) A true random sequence will not really repeat itself, but a duplicate value will show up early. Try the following:

local frandom = assert(io.open("/dev/urandom", "rb"))

local function ranval()
    local s = frandom:read(4)
    assert(s:len() == 4)
    local v = 0
    for i = 1, 4 do
        v = 256 * v + s:byte(i)
    end
    return v
end

local values = {}

for i = 1, math.huge do
    local v = ranval()
    if values[v] then
        print(i)
        break
    end
    values[v] = true
end


'ranval' generates a random value between 0 and 2^32-1. As you can see duplicates show up early. This is an application of the 'birthday paradox'.

In general if you want N unique random values you will need (far) more than N^2 possible outputs from you random generator.

Gé


On May 15, 2008, at 4:31 PM, Jorge Visca wrote:

Petite Abeille wrote:
If the quality of the PRNG is important to you, don't use math.random :)
Oh, it's not cryptographic stuff, just unique-ish identifier creation,
for runtime lived entities. The only danger is the cicle size... I don't
know the technical term for that, when the random secuence starts to
repeat itself. I seem to remember in old Turbo Pascal you could even
specify the secuence length.

Well, thanks for all the pointers (and code!). Seems like taping into
/dev/random is the way to go.

Jorge


--
Gé Weijers
ge@weijers.org