math.random() can generate a real number between 0 and 1 or between two integers. I wrote a function that extends this to a random number between any two floats. I fear that I did a horribly inefficient job, so I’m hoping somebody can do it in fewer lines. Give it a go!
--- Generates a random number between any two floats (inclusive)
-- @param min The lower bound of the random function
-- @param max The upper bound of the random function
local function GetRandom(min, max)
local minDecimalMatch = string.match(tostring(min), ".%d+")
local maxDecimalMatch = string.match(tostring(max), ".%d+")
local minNumDecimals = minDecimalMatch and #minDecimalMatch - 1 or 0
local maxNumDecimals = maxDecimalMatch and #maxDecimalMatch - 1 or 0
local multiplier = 10 ^ math.max(minNumDecimals, maxNumDecimals)
return math.random(min * multiplier, max * multiplier) / multiplier
end
-- Examples
GetRandom(0.1, 0.2) --> [0.1, 0.2]
GetRandom(0.1234, 123) --> [0.1234, 123.0000]
Is there any reason you don’t want to use RandomObject:NextNumber(min, max)?
I don’t see a reason for implementing this yourself, when roblox already did.
I believe this is probably the shortest and most efficient solution you can get.
There is actually a much simpler way to do this. If you think about it as a number line, you are starting a base number and adding a random amount bounded by 0 and the delta between them. This means you can take the minimum and add it by the delta times a random float.
Ex:
local function GetRandom(Min,Max)
local Delta = Max - Min
local RandomAddition = Delta * math.random()
return Min + RandomAddition
end
Compact example:
local function GetRandom(Min,Max)
return Min + ((Max - Min) * Delta)
end
Alternatively, you can go with the Random library as stated above for something like this:
local SingletonRandom = Random.new(tick())
local function GetRandom(Min,Max)
return SingletonRandom:NextNumber(Min,Max)
end
Neither solution that has been offered technically fits your specification (my emphasis added).
Random:NextNumber(min, max) returns a number in the interval [min, max)[1]. It is inclusive of min but not of max.
math.random returns a number in the interval [0, 1).[2] It is inclusive of 0 but not of 1. So the solution with the formula will not quite work either.
Having said that, if you’re happy with your output interval actually being [min, max) rather than [min, max], and since you specified that this is code golf, here is how you can golf it right down in vanilla Lua (this is normally judged by number of non-whitespace characters, making line count irrelevant):
function q(a, b)
return a + math.random() * (b - a)
end