Math.random Outputs Duplicate Results

math.random() outputs duplicate results from time to time. Take a look at this very simple server script:

-- Random seed
math.randomseed(tick())	
	
-- Loop
for i = 1, 20 do
	local position = Vector3.new(math.random(-2400, 2400)/10, math.random(70,120), math.random(-2400, 2400)/10)
	print(position)
	wait(0.1)
end

When I run this in studio, every now and then, I get numbers that are exactly the same as the previous numbers. Here is a sample output. Note the lines in bold are the duplicates.

-205.5, 114, 238.100006
-239.399994, 98, -147.199997 (x2)
148.199997, 99, -9.69999981
-239.399994, 98, -147.199997
-71.9000015, 115, 155
-239.399994, 98, -147.199997
118.400002, 78, 172.300003
148.199997, 99, -9.69999981 (x2)
101.099998, 96, -94.0999985
-71.9000015, 115, 155
118.400002, 78, 172.300003
-232.899994, 74, -65.0999985
101.099998, 96, -94.0999985
-169.300003, 78, 234.5
-26.1000004, 76, -237.800003
148.199997, 99, -9.69999981
-235.800003, 89, 15.1999998
-71.9000015, 115, 155

Repro File Attached:
Random Number Test.rbxl (14.2 KB)
Press Run in Studio several times until you see duplicates printed.

1 Like

If you put this code after the math.randomseed call, does it still happen as often?

for i=1,50 do
   math.random() -- throw away the first few values
end

The entropy of the first random numbers that math.random provides can be really bad depending on where you are running this and what seed you are providing, so if you just throw those away the “randomness” might improve.

EDIT: tried it and it didn’t help. Aside from that though, math.random just has terrible randomness, since it is based directly on the C implementation for random numbers (rand).

2 Likes

Oddly enough, I noticed that if I remove the wait() in the loop, then the duplicates happen less often.

It’s probably because another script is setting duplicate math.randomseed’s. If randomness is important, consider implementing your own PRNG

The code I posted above is the entirety of the code. I have added no other scripts in the game.

It could also be a roblox script or a plugin