Murga-Projects Forums
math.random(what?) - Printable Version

+- Murga-Projects Forums (
+-- Forum: Project Forums (/forumdisplay.php?fid=1)
+--- Forum: MurgaLua - General (/forumdisplay.php?fid=2)
+--- Thread: math.random(what?) (/showthread.php?tid=137)

math.random(what?) - mikshaw - 07-27-2007 09:08 AM

I was debating whether to start a general "please help mik with everything he doesn't understand" thread, since I think there will be a lot in the coming months, but I guess while the forums are still relatively slow I'll stick with one thread per subject.

The current thing I can't figure out is the math.random function, which I assume is supposed to return a pseudo-random number. However, it seems to return the same number every time.
If I use no argument the result is always 0.84018771715471
math.random(6) or math.random(1,6) always returns 6
math.random(1,12) always returns 11
...and on and on with these seemingy illogical results

Does this function not work the way it should, or am I just not understanding the Lua documentation?

RE: math.random(what?) - iGame3D - 07-27-2007 10:06 AM

ok first you want to set the random seed so that the machine actually initializes a sorta psuedo randomness.


Now you should get a decently random number, especially when its called more than once since the seed will change, once is usually enough.

Random numbers were the very first thing I tried in Lua since I
used tons and tons of random-icity back 1983 with BASIC
and then later with my very many strange iGame3D experiments.

RE: math.random(what?) - mikshaw - 07-27-2007 01:37 PM


Thanks very much.
The problem now is that I have no idea why that works. I've seen the term "random seed" used in many other places, but never understood what it means. And why does the random seed apparently need to be different each time?

RE: math.random(what?) - iGame3D - 07-27-2007 03:16 PM

Not sure I can explain it.

Basically computers can not create true randomness since everything they do is based on a calculation which can only done with given parameters.

By seeding it with a value that is not its default it has a new parameter to play with.

The random seed does not need to constantly change, it only needs to be called once, but by updating the seed its more likely to give you the appearance of greater randomness.

Although other programmers argued against my technique,
I just feel its more random if I use two random numbers:

If random number A is greater than some value, then roll random number B and use that, else just use random number A.

I guess they had a point that I was using an extra cycle or something.
But I doubt my gigaflops calculating computer is going to care.