From 1a7868c1d55592a59f6ffa75ad1bd6330282b7fe Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Sat, 27 Dec 2014 18:32:26 -0200 Subject: [PATCH] bug: 'random' limit is 2^31-1, not RAND_MAX --- lmathlib.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lmathlib.c b/lmathlib.c index a643ef73..1925e826 100644 --- a/lmathlib.c +++ b/lmathlib.c @@ -1,5 +1,5 @@ /* -** $Id: lmathlib.c,v 1.112 2014/11/02 19:19:04 roberto Exp roberto $ +** $Id: lmathlib.c,v 1.113 2014/11/07 11:31:58 roberto Exp roberto $ ** Standard mathematical library ** See Copyright Notice in lua.h */ @@ -27,9 +27,11 @@ #if defined(LUA_USE_POSIX) #define l_rand() random() #define l_srand(x) srandom(x) +#define L_RANDMAX 2147483647 /* (2^31 - 1), following POSIX */ #else #define l_rand() rand() #define l_srand(x) srand(x) +#define L_RANDMAX RAND_MAX #endif #endif /* } */ @@ -233,12 +235,12 @@ static int math_max (lua_State *L) { /* ** This function uses 'double' (instead of 'lua_Number') to ensure that -** all bits from 'l_rand' can be represented, and that 'RAND_MAX + 1.0' +** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0' ** will keep full precision (ensuring that 'r' is always less than 1.0.) */ static int math_random (lua_State *L) { lua_Integer low, up; - double r = (double)l_rand() * (1.0 / ((double)RAND_MAX + 1.0)); + double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0)); switch (lua_gettop(L)) { /* check number of arguments */ case 0: { /* no arguments */ lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */