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
5 years ago
Edited 5 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.

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

3 answers

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

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

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

You can use

1Random.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:

1local rand = Random.new()
2 
3for i = 1,10 do
4    print(rand:NextNumber()*10)
5end

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

1local rand = Random.new()
2 
3function makeRand(place) --where place is 10^places to move the decimal
4    place = place or 1
5    return rand:NextNumber()*(10^place)
6end
7 
8print(makeRand())
9print(makeRand(5))

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

01local rand = Random.new()
02 
03function makeRand(min,max) --where place is 10^places to move the decimal
04    local diff = max - min
05    local nrand = rand:NextNumber()
06    nrand = nrand*diff --percent of the difference between the two
07    return min + nrand --offset by the difference.
08end
09 
10print(makeRand(100,5000))
11print(makeRand(-10,10))
Log in to vote
0
Answered by 5 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.

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

Answer this question