Math.random upper limit

I haven’t gotten any news about the changes in math.random, but it seems like there is an upper limit of 1e10.

math.random(1,1e10) --would error which I don't think it did before. 

image

Before anyone starts yelling at me for using large numbers. I just want to tell them that it causes minor inconviences. Mostly when you want more accurate data for very low draw chances in chests. Is the reason for this limit due to long calculation done in the background by roblox if the number gets too high? I know math.huge can be used outside math.random, but I would imagine math.random(1,math.huge) would cause crash on roblox. Does anyone know what the exact limit is so I can make sure accidental values above are set to the limit?

I heard that Random.new() is way better than math.random(). You could try using something like:

local random = Random.new()
local e1 = random:NextInteger(1, limit)
local e2 = random:NextNumber(1, limit)

math.huge/1e10 seems to work with Random.new() though I wouldn’t do that.

4 Likes

Thank you for pointing out the function. I had hear about it but wasn’t thinking much of using it. Specially the NextNumber call is excellent for my application.

1 Like

No problem, glad to help! :grin:

math.random overload for 2 arguments is 32-bit signed integers for both of them.
Luau overflows signed 32-bit integers greater or equal than 231 to exactly -232, though this is unusual as it’s generally wrapped around as it’s casted to 32-bit signed integer C-wise.

The exact limit pretty much depends the implementation of Lua and how Lua is compiled. In Luau it’s the maximum value of 32-bit signed integers. In vanilla Lua 5.2, it can pretty much take all doubles.


math.huge/1e10 is the same as math.huge. IEEE Infinity, signed or unsigned, divided by any Lua “number” (floating point value specified in the IEEE 754 format), except for (+/-)Infinity and the NaNs, will result in (+/-)Infinity (depending on the sign bit) so I’m not sure why you’re including /1e10 in math.huge/1e10.
The reason why it works is because for NextInteger it is casted to int64, in Luau, to the minimum 64-bit signed integer it can take.
For NextNumber, I presume it runs the algorithm without checking if the value is finite.

3 Likes