lua-users home
lua-l archive

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


> The Lua Wiki Math Library Tutorial page[1] says:
> "But beware! The first random number you get is not really 'randomized'
> (at least in Windows 2K and OS X)."

I have confirmed that this actually happens in Mac OS X. Rici Lake has
checked FreeBSD and the same happens there, for a reason: they both share
a BSD code basis.

Anyway, the problem seems to be that when the seeds differ very little
the first value of generated by BSD rand() also differ very little. This
difference is lost when Lua converts the integer returned by rand() into
a real number, effectively preserving only the high bits in the result.
When you call math.random(1,100) from Lua, the low-bit difference vanishes
and you see the same integer result.

The Windows code is probably different but not in any essential way: rand
probably uses a classical Linear congruential generator and the same loss
of bits will occur.

Lua relies on rand from libc. It must not be too clever about what it does
with the result of rand lest it breaks its randomness (which may be weak
already). So I think the fix for Lua is to call rand() a couple of times
whenever the seed changes.
--lhf