[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Why is the first random number after randomseed() not random?
- From: Luiz Henrique de Figueiredo <lhf@<a href="/cgi-bin/echo.cgi?tecgraf.puc-rio.br">...</a>>
- Date: Mon, 19 Mar 2007 20:09:59 -0300
> The Lua Wiki Math Library Tutorial page 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.