I found this:
http://devwiki.metaplace.com/wiki/index ... in_a_range
And this:
http://ardoris.wordpress.com/2008/11/07 ... es-in-lua/
So, this should work. I think.
Code: Select all
function random(min, max, precision)
local precision = precision or 0
local num = math.random()
local range = math.abs(max - min)
local offset = range * num
local randomnum = min + offset
return math.floor(randomnum * math.pow(10, precision) + 0.5) / math.pow(10, precision)
end
EDIT: Here's a slightly different version (when
precision is
nil, it doesn't round the random number at all):
Code: Select all
function randomFloat(min, max, precision)
-- Generate a random floating point number between min and max
--[[1]] local range = max - min
--[[2]] local offset = range * math.random()
--[[3]] local unrounded = min + offset
-- Return unrounded number if precision isn't given
if not precision then
return unrounded
end
-- Round number to precision and return
--[[1]] local powerOfTen = 10 ^ precision
local n
--[[2]] n = unrounded * powerOfTen
--[[3]] n = n + 0.5
--[[4]] n = math.floor(n)
--[[5]] n = n / powerOfTen
return n
end
Example run-through:
randomFloat(1, 10, 3)
1: range = max - min
10 - 1
9
2: offset = range * math.random()
9 * (0.0 to 1.0)
(0.0 to 9.0)
3: unrounded = min + offset
1 + (0.0 to 9.0)
(1.0 to 10.0)
Example unrounded number: 1.23456789
Rounded to three decimal places: 1.235
1: 10 ^ precision (3 in this example)
1000
2: 1.23456789 * 1000
1234.56789
3: 1234.56789 + 0.5
1235.0678
4: Floor of 1235.06789
1235
5: 1234 / 1000
1.235
Written more concisely:
Code: Select all
function randomFloat(min, max, precision)
local range = max - min
local offset = range * math.random()
local unrounded = min + offset
if not precision then
return unrounded
end
local powerOfTen = 10 ^ precision
return math.floor(unrounded * powerOfTen + 0.5) / powerOfTen
end