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.
1 | local rand = math.random( 1999999 , 3999999 )/ 1000000 |
You can use the following formula to get a random number with decimals in it:
1 | min = 10 |
2 | max = 20 |
3 | rand = min + 0.5 + math.random() * ( max - min ) |
4 | print (rand) |
You can use
1 | 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:
1 | local rand = Random.new() |
2 |
3 | for i = 1 , 10 do |
4 | print (rand:NextNumber()* 10 ) |
5 | end |
or if you wanted to even make it a function to be more useful,
1 | local rand = Random.new() |
2 |
3 | function makeRand(place) --where place is 10^places to move the decimal |
4 | place = place or 1 |
5 | return rand:NextNumber()*( 10 ^place) |
6 | end |
7 |
8 | print (makeRand()) |
9 | print (makeRand( 5 )) |
to further this, incase you wanted to use this within a range you can do something like:
01 | local rand = Random.new() |
02 |
03 | function 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. |
08 | end |
09 |
10 | print (makeRand( 100 , 5000 )) |
11 | print (makeRand(- 10 , 10 )) |
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.
1 | local r = math.random( 1 * 10 ^ 5 , 5 * 10 ^ 5 )/ 10 ^ 5 |
2 | print (r) |