I am making a script that plays a Sound every time the player’s Humanoid takes damage. The PlaybackSpeed of the Sound is supposed to randomly change to any number between 0.9 and 1.1, but I currently do not know how to do this without setting up an excruciatingly long table of possible values. I tried using a solution I Googled (there were little to no results) that used math.random, but I obviously did something wrong because it is picking numbers outside of the range:
Ouch.PlaybackSpeed = math.random(9)/11
One of the random outputs: 0.090909093618393
local RNG = Random.new(tick())
for i = 1, 10 do
local random_number = RNG:NextNumber(0.9, 1.1)
print(("Our next random number is: %s"):format(random_number))
end
Output will be something like:
Our next random number is: 1.0571754411884
Our next random number is: 0.97491074296206
Our next random number is: 0.97687826467788
Our next random number is: 0.96483255566682
Our next random number is: 1.0297381383331
Our next random number is: 1.0022596426323
Our next random number is: 0.98034686206397
Our next random number is: 1.0964522742403
Our next random number is: 0.99467616375973
Our next random number is: 0.92166707067802
It doesn’t need to be 5 lines, that was purely just to demonstrate it works
local RNG = Random.new(tick())
--> When we need a random number:
print(RNG:NextNumber(0.9, 1.1))
--[!] or, even:
print(Random.new():NextNumber(0.9, 1.1))
I imagine the issue with your solution, although functional, only returns a pseudo-random integer. This is due to the way math.random functions - when given two integers as an argument it returns a uniformally generated random integer within that range.
That’s why @Auxintic created a function to get a random number with more digits by not passing any arguments to the math.random function. When called with no arguments it returns a uniform, real number between 0 to 1
Yours kind of works, but it only seems to get 0.9, 1 and 1.1. Unrelated to your solution, but for some reason the actual playbackspeed looks different:
(Actual playbackspeed on bottom)
@Mystyle48
I imagine this may be some kind of floating point error, or possibly some other issue within the Engine.
@ArrantNickel
Again, it’s not that solution doesn’t work - it’s just that OP wanted a real number, not an integer and your solution provides only integers when calling math.random(9, 11) therefore you can only get 0.9, 1, and 1.1 when dividing the result by 10. You can learn more here: math | Documentation - Roblox Creator Hub