lua-users home
lua-l archive

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


In math_random(), whether rand() returns 0 or RAND_MAX, the result of
math_random() would be 0. It should modulo RAND_MAX + 1 instead of
modulo RAND_MAX.

--- lua-5.1.4/src/lmathlib.c
+++ lua-5.1.4/src/lmathlib.c
@@ -181,7 +181,7 @@ static int math_max (lua_State *L) {
 static int math_random (lua_State *L) {
   /* the `%' avoids the (rare) case of r==1, and is needed also because on
      some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
-  lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
+  lua_Number r = (lua_Number)(rand()%(RAND_MAX + 1)) /
(lua_Number)(RAND_MAX + 1);
   switch (lua_gettop(L)) {  /* check number of arguments */
     case 0: {  /* no arguments */
       lua_pushnumber(L, r);  /* Number between 0 and 1 */