I've been using math.random for my whole game as I find it easy to use, but there are concerns math.random returns the same numbers sometimes, whilst Random.new does not. Is it worth changing my math.random to Random.new in my scripts? I want to have the most random results I can get.
There is no longer a difference.
Roblox changed math.random to use a Random object under the hood. But the Random class still has its own benefits such as having a "local" seed.
For example if you did math.randomseed(seed)
this would be a global change; all scripts are affected.
Where as with the Random class you can do Random.new(seed)
and that seed will not affect other scripts.
Roblox's Random and Lua's math.random are pseudo random number generators
where pseudo
means fake
so pseudo random literally means fake random
.
A random number generator that is considered "true random" can be found at random.org and is considered true random because it uses atmospheric noise
, and everything on this "true random number generator" can be found on that website.
Use whichever you want. There should not be a difference in quality of the "randomness".
both are equally good at giving random numbers; although if u asked me i prefer random.new as u get to specify which seed u want to use, giving that extra customizeability(tho technically it wont make a difference cus all seeds are equally random)
Currently, math.random(num1,num2) returns a whole number, there might be cases where you want a float. You can use math.random() but it returns a number between 0 to 1. This is where Random can prove to be useful
local RandomNum = Random.new() -- you can provide a seed if you want local Number = RandomNum:NextNumber(num1,num2) -- NextNumber returns a float between num1 and num2 local Number2 = RandomNum:NextInteger(num1,num2) -- NextInteger returns a integer between num1 and num2 print(Number)
Random has a very odd thing about it, you can clone it and it will preserve it's current state.
local RandomNum = Random.new(tick()) local RandomNum2 = RandomNum:Clone() print(RandomNum:NextInteger(1,10),Random2:NextInteger(1,10)) -- they will print the same value
It all depends on what you are trying to accomplish. If it's for general uses like choosing a random element in an array, then you should stick with math.random. However, if you're looking for precise numbers then it's better if you use Random:NextNumber
I hope this helps.