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

Problem with Random Seeding (and solution)

Started by rainbowparade, 11 March 2016 - 11:28 PM
rainbowparade #1
Posted 12 March 2016 - 12:28 AM
Just posting this here so that it hits google as I could not find this answer here.

As we know, we are supposed to seed the random number by


math.randomseed(os.time())

And as far as I can tell, that is our best chance at a seed.

I have been experimenting with random generation in bots, recently and noticed a very predictable behaviour with at the very least the current version of CC in Resonant Rise on my computer (average 64bit java Win8 machine). It is probably the case in all CC as it is underlying OS stuff.

What I noticed is that I could run an os.time() seeded program quite a number of times with zero variance - the exact same random numbers.

So, I've investigated and it turns out that on my machine, at least, os.time() actually returns a floating point number where the whole number represents a minute. It is 10.17am, which means my seed is 17.XXX.

As randomseed() obviously ignores the floating point portion of the seed, if you deploy/run in maybe even the same minute OR the 17th minute of the next hour, you will get the exact same random generation.

So if you have this problem, I suggest seeding the random with os.time() multiplied by at least 1000 as it is quite clearly ignoring the floating point portion of the os.time() that I am getting. That will bring the seconds / milliseconds into the usable portion of seed.

Right now, as it stands, if you get the same os.time() as me, you are only actually seeding the random with 1 of 60 numbers which is not good for sending out 500 bots, like I did recently :-)

Hope this helps anybody wondering about the same thing.

CC is a lot of fun, by the way.
Lyqyd #2
Posted 12 March 2016 - 12:52 AM
In ComputerCraft, os.time returns the current in-game time, so if it is, in fact, truncating to an integer, there are only 24 seeds possible when using os.time.
Bomb Bloke #3
Posted 12 March 2016 - 01:27 AM
ComputerCraft sets a random seed for you, unlike some other Lua environments. I'll admit I'm unsure as to what it bases it on.
rainbowparade #4
Posted 12 March 2016 - 02:24 AM
In ComputerCraft, os.time returns the current in-game time, so if it is, in fact, truncating to an integer, there are only 24 seeds possible when using os.time.

Oh really?

That's rather interesting. I suppose there would be some genuine utility to that.

Wow, so, it was just a pure coincidence that I happened to print out os.time() and get 17 at the 17th minute of the hour

ComputerCraft sets a random seed for you, unlike some other Lua environments. I'll admit I'm unsure as to what it bases it on.

I never thought to try it unseeded. Wonder if it is any better than running with os.time() * 1000 (which turns out to be perfectly adequate)