Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

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

Asked by
piRadians 297 Moderation Voter
6 years ago

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

Log in to vote
0
Answered by
RAYAN1565 691 Moderation Voter
6 years ago
Edited 6 years ago

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)
0
Thanks. :D piRadians 297 — 6y
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. EmilyBendsSpace 1025 — 6y
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. RAYAN1565 691 — 6y
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. EmilyBendsSpace 1025 — 6y
Ad
Log in to vote
1
Answered by 6 years ago

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.

Answer this question