lua-users home
lua-l archive

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




Sent from my iPad
> On Mar 1, 2018, at 12:31 AM, William Ahern <william@25thandClement.com> wrote:
> 
>> On Wed, Feb 28, 2018 at 07:32:47PM -0800, Bruce Hill wrote:
>> I was doing some testing that involved generating very large random integers
>> and I noticed a bug in Lua 5.3.4's math.random(). If you pass in a range
>> larger than 2^31-1 (L_RANDMAX), math.random() will generate random integers
>> that only have 31 bits of randomness. For example, this code will run
>> without errors:
>> 
>>    for _=1,1000000 do
>>        assert(math.random(0, 0x7fffffffffffffff) & 0xffffffff == 0)
>>    end
>>    print("The lowest 32 bits were always zero!")
>> 
>> The fix for this is pretty simple:
>> 
>>> ** $Id: lmathlib.c,v 1.119 2016/12/22 13:08:50 roberto Exp $
>> 269,270c269
>> <   luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
>> <                    "interval too large");
>> ---
>>>  luaL_argcheck(L, up - low + 1 <= L_RANDMAX, 1, "interval too large");
> 
> up - low isn't representable when the difference is greater than
> LUA_MAXINTEGER.
> 

I am not so sure the original version is wrong, since it does
not claim that all bits returned must be random, it just check
if the interval is too large (with lua integer). If the error message 
were "not all bits are random", the patch make sense.

It might be more useful to add more random bits if the interval 
is over L_RANDMAX, and not just quit . For my own use,
I patched math.random with Knuth srand64 instead of gcc rand().

rand() is not that good (at least my copy of gcc):

http://www.azillionmonkeys.com/qed/random.html