lua-users home
lua-l archive

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


> 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.
> 

low >= 0 test not needed ?

Tried the assert on my Windows machine, I only get 16 bits randomness.
Probably less because it uses rand(), which is not that good.

Is there a compiler flag that let me get 32 bits randomness ?