Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make make math.random() return a float value?

I know you can do that by simply doing math.random() with no parameters, but how would I make it a float between certain numbers?

local random = math.random(5,15)
print(random) -- note, I want this to return a decimal/float value between 5 and 15. Is that possible? if so, how?

2 answers

✓ Accepted answer

Depends how many decimal places you want. If I want one decimal place then I'd do the following:

local value = math.random(50, 150)
local valueAdjusted = value/10

print(valueAdjusted)

If you want more decimal places, just add more zeroes. For instance, three decimal places:

local value = math.random(5000, 15000)
local valueAdjusted = value/1000

print(valueAdjusted)

4 comments

0

Thanks. :D

0

This is not generally what people are looking for when they want a float between two values. They usually want ALL floats in the range to be possible outcomes. For example, the first option of math.random(50,150)/10 only has 101 possible values.

0

@EmilyBendsSpace for one decimal place, it includes all possible outcomes. It is technically impossible to gather all floats since the computer must stop at a certain point within decimals.

0

@RAYAIN1565 With all due respect, there is a fundamental misunderstanding here. "floats" does not mean real numbers. There are a finite number of floating-point numbers between 0 and 1 (for any format, e.g. IEEE754), and it's possible to make use of them all, but not with the method you've shown.

The best practice now is to use the Random class like this:

 local rng = Random.new()
 local r = rng:NextNumber(5,15)

You can optionally seed Random.new() with a seed value, useful when you want to test with the same random sequence.

You could use math.random() to get the same range, like this:

local r = 5 + 10 * math.random()

But there is no real advantage to this. math.random() internally uses the new Random class, but a global instance of it, and with additional overhead of a conditional to check a FFlag, and another branching to cover the cases where math.random(a,b) is expected to return an integer.

So, basically, don't use math.random. It was patched to use the new PRNG to improve the randomness in existing code (over the old C rand() implementation), but there is no reason to use it for new work.

This discussion is preserved as it was. New answers, comments, and votes are closed.