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

I just tried: print(math.random(999999999999)) and printed 1 .

Also, any math.random() that includes 999999999999 prints the same thing. Some 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)} do print(v) end 

" 1

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

" true

Then I think you understand (if you know, of course, Lua). Can you explain to me?

@Edits:

The Lua version used by me is 5.2.

I also tried print(math.random(-999999999999)) and printed 111711452 . It looks like it worked like a positive number.

+5
source share
1 answer

This problem, of course, is due to the fact that math.random processes input arguments passed in Lua 5.1 and / or 5.2. From [mathlib.c] 1 :

As you know in C , the standard int can represent the values -2,147,483,648 - 2,147,483,647 . Adding +1 to 2,147,483,647 , as in your use case, will overflow and wrap a value giving -2,147,483,648 . The end result is negative, since you multiply the positive with a negative number.

There are several ways to fix this problem:

  • Update the latest version of Lua version 5.3. Since then, this has fixed this problem by treating the input arguments as lua_Number.
  • Switch to LuaJIT, which does not have this integer overflow problem.
  • Correct and recompile the source of Lua 5.1 and / or 5.2.
  • Change your random range so that it doesn't overflow

And for your last request, read the documentation: http://lua-users.org/wiki/MathLibraryTutorial

Pay attention to the last lines:

math.random(upper) generates integers between 1 and the top . top and bottom must be integer. In another case, Lua throws an integer from above, sometimes giving math.floor(upper) and other math.ceil(upper) , with unexpected results (same for lower).

+5
source

Source: https://habr.com/ru/post/1270865/


All Articles