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

Can you make a random number that isn't an integer?

Asked by
Plieax 66
4 years ago
Edited 4 years ago

I was just wondering if there is a better way to make random numbers with decimals, example

math.random.random(2,4) would return 2.5214523 or 3.56363 or if I have to use my method of taking the integer and then dividing it by 1000000 My way works, it just feels like there should be an easier way.

local rand = math.random(1999999,3999999)/1000000

3 answers

Log in to vote
1
Answered by
royaltoe 5144 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

You can use the following formula to get a random number with decimals in it:

min = 10
max = 20
rand = min + 0.5 + math.random() * ( max - min )
print(rand)
0
This does work, but I guess this means the answer to the question is no, thank you! Plieax 66 — 4y
Ad
Log in to vote
0
Answered by
Vathriel 510 Moderation Voter
4 years ago
Edited 4 years ago

You can use

Random.new():NextNumber()*10

although I'd suggest not deleting random objects right after you use them once as that'd get expensive.

So maybe something more like:

local rand = Random.new()

for i = 1,10 do
    print(rand:NextNumber()*10)
end

or if you wanted to even make it a function to be more useful,

local rand = Random.new()

function makeRand(place) --where place is 10^places to move the decimal
    place = place or 1
    return rand:NextNumber()*(10^place)
end

print(makeRand())
print(makeRand(5))

to further this, incase you wanted to use this within a range you can do something like:

local rand = Random.new()

function makeRand(min,max) --where place is 10^places to move the decimal
    local diff = max - min
    local nrand = rand:NextNumber()
    nrand = nrand*diff --percent of the difference between the two
    return min + nrand --offset by the difference.
end

print(makeRand(100,5000))
print(makeRand(-10,10))
Log in to vote
0
Answered by 4 years ago

unfortunately roblox does not have any easier method to get random number that has decimals unless you pull off a massive stunt with math.pi. You can always use scientific notation to spare your eyes from looking at all those 0s or 9s you put in.

local r = math.random(1*10^5,5*10^5)/10^5
print(r)

Answer this question