Why does math.random(999999999999) returns 1 in Lua? -


i tried: print(math.random(999999999999)) , has printed 1.

also math.random() includes 999999999999 printing same thing. examples:

print(math.random(1.999999999999)) » 1

print(math.random(1999999999999)) » 1

for k,v in next,{math.random(999999999999), math.random(1999999999999), math.random(2.999999999999)}     print(v) end 

» 1

local n = math.random(999999999999) print(n==1) 

» true

then think understood (if know lua of course). can explain me?

@edits:

the lua version i'm using 5.2.

i tried print(math.random(-999999999999)) , printed 111711452. looks worked positive number.

this problem surely because math.random treats input arguments passed in lua 5.1 and/or 5.2. [mathlib.c]1:

as may know in c, standard int can represent values -2,147,483,648 2,147,483,647. adding +1 2,147,483,647, in use-case, overflow , wrap around value giving -2,147,483,648. end result negative since you're multiplying positive negative number.

there few ways rectify , handle problem:

  1. upgrade latest lua version 5.3 . 1 has since fixed issue treating input arguments lua_number instead.
  2. switch luajit not have integer overflow issue.
  3. patch lua 5.1 and/or 5.2 source fix , recompile.
  4. modify random range not overflow

and last query read documentation:http://lua-users.org/wiki/mathlibrarytutorial

notice last line quotes:

math.random(upper) generates integer numbers between 1 , upper.upper , lower must integer. in other case lua casts upper integer, giving math.floor(upper) , others math.ceil(upper), unexpected results (the same lower).


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -