bug: 'random' limit is 2^31-1, not RAND_MAX

This commit is contained in:
Roberto Ierusalimschy 2014-12-27 18:32:26 -02:00
parent de3933480e
commit 1a7868c1d5

View File

@ -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 */