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

How to make math.random return a decimal value between .1 and .3?

Asked by 6 years ago

I need a code to wait between .1 - .3 seconds:

wait(math.random(.1,.3))

So I would assume this would pick a number between .1 and .3, but the thing is going ridiculously fast.

So then I just put into the output:

print(math.random(.1,.3))

Every single time I get 0. I need to know why this is and how I can actually randomly get a decimal value between .1 and .3.

3 answers

Log in to vote
-1
Answered by 6 years ago

If I recall correctly, math.random only returns whole values.

math.random(10,30)/100)

0
Well that's unfortunate. Do you know of how I could randomly select between .1 and .3 on my wait function? captiongoosebut 19 — 6y
0
dang it, your solution is smarter than mine xD cmgtotalyawesome 1418 — 6y
0
This is a good solution thank you very much. captiongoosebut 19 — 6y
1
An issue with this is that you will only get numbers with a precision of 2 decimal places. Eg. you will only be able to get "0.01, 0.45, 0.20", and not "0.111232, 0.3432, 0.75848754" WillieTehWierdo200 966 — 6y
0
If you want to be more specific, add more 0's to get a more precise decimal place. But I didn't see the need to calculate past the hundredth YTRaulByte 389 — 6y
Ad
Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

The new Random feature supports floating point min/max values:

local random = Random.new()
local number = random:NextNumber(0.1, 0.3)

I'm aware that an answer has already been accepted, but I believe this to be the better solution because Random produces better random numbers than math.random currently, the syntax of Random.NextNumber is more intuitive, and the resulting random number will be more granular than dividing a random integer by 100 as in the previously accepted answer.

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
6 years ago

math.random has three modes:

  • math.random(low, high) produces an integer between (inclusively) integers low and high
  • math.random(high) is the same as math.random(1, high)
  • math.random() produces a real number between 0 (inclusively) and 1 (exclusively).

You can "shrink" and "shift" the interval [0, 1) to become [.1, .3):

[0, 1) * 0.2 is [0, 0.2). [0, 0.2) + 0.1 is [0.1, 0.3).

In general, you can use the idiom low + (high - low) * math.random() to generate real numbers between low and high:

for i = 1, 10 do
    print(0.1 + 0.2 * math.random())
end

-- 0.26803754335269
-- 0.17887658532709
-- 0.25661984467879
-- 0.25968800662085
-- 0.28232947150245
-- 0.13951027384028
-- 0.16704455111176
-- 0.25364591889083
-- 0.15555494213477
-- 0.21079399110749

Answer this question