diff options
author | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2014-12-27 18:32:26 -0200 |
---|---|---|
committer | Roberto Ierusalimschy <roberto@inf.puc-rio.br> | 2014-12-27 18:32:26 -0200 |
commit | 1a7868c1d55592a59f6ffa75ad1bd6330282b7fe (patch) | |
tree | db7facd15907e6321e2a4909e6f26dbe09f6bc18 /lmathlib.c | |
parent | de3933480e729577355b18c086d2e3c341c17aa6 (diff) | |
download | lua-1a7868c1d55592a59f6ffa75ad1bd6330282b7fe.tar.gz lua-1a7868c1d55592a59f6ffa75ad1bd6330282b7fe.tar.bz2 lua-1a7868c1d55592a59f6ffa75ad1bd6330282b7fe.zip |
bug: 'random' limit is 2^31-1, not RAND_MAX
Diffstat (limited to 'lmathlib.c')
-rw-r--r-- | lmathlib.c | 8 |
1 files changed, 5 insertions, 3 deletions
@@ -1,5 +1,5 @@ | |||
1 | /* | 1 | /* |
2 | ** $Id: lmathlib.c,v 1.112 2014/11/02 19:19:04 roberto Exp roberto $ | 2 | ** $Id: lmathlib.c,v 1.113 2014/11/07 11:31:58 roberto Exp roberto $ |
3 | ** Standard mathematical library | 3 | ** Standard mathematical library |
4 | ** See Copyright Notice in lua.h | 4 | ** See Copyright Notice in lua.h |
5 | */ | 5 | */ |
@@ -27,9 +27,11 @@ | |||
27 | #if defined(LUA_USE_POSIX) | 27 | #if defined(LUA_USE_POSIX) |
28 | #define l_rand() random() | 28 | #define l_rand() random() |
29 | #define l_srand(x) srandom(x) | 29 | #define l_srand(x) srandom(x) |
30 | #define L_RANDMAX 2147483647 /* (2^31 - 1), following POSIX */ | ||
30 | #else | 31 | #else |
31 | #define l_rand() rand() | 32 | #define l_rand() rand() |
32 | #define l_srand(x) srand(x) | 33 | #define l_srand(x) srand(x) |
34 | #define L_RANDMAX RAND_MAX | ||
33 | #endif | 35 | #endif |
34 | #endif /* } */ | 36 | #endif /* } */ |
35 | 37 | ||
@@ -233,12 +235,12 @@ static int math_max (lua_State *L) { | |||
233 | 235 | ||
234 | /* | 236 | /* |
235 | ** This function uses 'double' (instead of 'lua_Number') to ensure that | 237 | ** This function uses 'double' (instead of 'lua_Number') to ensure that |
236 | ** all bits from 'l_rand' can be represented, and that 'RAND_MAX + 1.0' | 238 | ** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0' |
237 | ** will keep full precision (ensuring that 'r' is always less than 1.0.) | 239 | ** will keep full precision (ensuring that 'r' is always less than 1.0.) |
238 | */ | 240 | */ |
239 | static int math_random (lua_State *L) { | 241 | static int math_random (lua_State *L) { |
240 | lua_Integer low, up; | 242 | lua_Integer low, up; |
241 | double r = (double)l_rand() * (1.0 / ((double)RAND_MAX + 1.0)); | 243 | double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0)); |
242 | switch (lua_gettop(L)) { /* check number of arguments */ | 244 | switch (lua_gettop(L)) { /* check number of arguments */ |
243 | case 0: { /* no arguments */ | 245 | case 0: { /* no arguments */ |
244 | lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */ | 246 | lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */ |