This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mrpoopy345's profile picture

Lua random bug or my stupidity?

Started by mrpoopy345, 04 April 2015 - 09:03 PM
mrpoopy345 #1
Posted 04 April 2015 - 11:03 PM
I was just playing around with math.random and I came across something. I was generating random numbers 1 to 100 and if the random number generated was the same as the previous random number generated it would tell me what cycle I'm on and break. This is the code I am using:

l = 0
for i = 1, 10000 do 
 prev = l
 l = math.random(1,100)
 if prev == l then
  print(i)
  break
 end
end
But for some reason this always outputs 25. Why?
Dog #2
Posted 04 April 2015 - 11:12 PM
Is it possible that it's generating a match at the 25th iteration each time? Add a print statement (e.g. print(l)) within the loop so you can see the numbers generated - that *should* let you see if that's the case or not.
mrpoopy345 #3
Posted 04 April 2015 - 11:15 PM
For some reason it is generating 1 on the 24th iteration and 25th iteration every time.
Dog #4
Posted 04 April 2015 - 11:23 PM
My understanding is that math.random isn't *really* random but just simulates randomness to a certain degree. This is probably a result of that limitation. I imagine there's a way to use the time and/or date, or some other information, as a way to ensure more randomness, but I'll have to defer to one of the pros as RNG theory is beyond me.
Bomb Bloke #5
Posted 04 April 2015 - 11:43 PM
Testing it myself in-game, I'm not getting that behaviour. The result is different for each execution.

Most PRNGs work by taking an unpredictable seed value, then generating a series of numbers based on that seed. Often, the system time is used. If the same seed is being used every time you start your script for some reason, then you'll get the same series of numbers every time.

I suspect you're running your script in an environment which is, for whatever reason, using a static seed.
mrpoopy345 #6
Posted 05 April 2015 - 01:33 PM
I am using vanilla lua, not in game computercraft lua which might be the cause. Even when I restart the cmd prompt it still produces the same random numbers for some reason.
Bomb Bloke #7
Posted 05 April 2015 - 01:40 PM
It appears you may be expected to manually set a seed:

math.randomseed( os.time() )
mrpoopy345 #8
Posted 05 April 2015 - 01:41 PM
I've read up on this, apparently in vanilla lua you have to use math.randomseed(os.time()) before generating random numbers. Problem solved!

EDIT: Ninja'd
Edited on 05 April 2015 - 11:41 AM