So after 6 long hours, a new library is born. It's too late to continue, but I'm thinking about adding Multiply-with-carry tomorrow.
2 algorithms:
Mersenne twister http://en.wikipedia.org/wiki/Mersenne_twister, very good and slow
Linear congruential generator http://en.wikipedia.org/wiki/Linear_con ... _generator, fast and, well, it works... kind of.
The LGC comes with 3 different pre-defined parameters.
Lua Code Sample:
Code: Select all
require('randomlua')
l1 = lcg(0) -- Linear congruential generator (Ansi C params)
l2 = lcg(0, 'nr') --Linear congruential generator (Numerical recipes params)
l3 = lcg(0, 'mvc') -- Linear congruential generator (Microsoft Visual C params)
c1 = mwc(0) -- Multiply-with-carry (Ansi C params)
c2 = mwc(0, 'nr') -- Multiply-with-carry (Numerical recipes params)
c3 = mwc(0, 'mvc') -- Multiply-with-carry (Microsoft Visual C params)
m = twister(0) -- Mersenne twister
for n = 1, 10 do
io.write(string.format("%8d%8d%8d%8d%8d%8d%16d\n", l1:random(0), l2:random(0), l3:random(0), c1:random(0), c2:random(0), c3:random(0), m:random(0)))
end
Code: Select all
12345 62303 40643 12345 62303 40643 1737743152
5758 10546 36474 58949 29249 61405 88390169
10207 63209 23381 58684 55448 60123 1910268388
7212 21300 8388 54232 58804 31419 2110758764
38645 58627 19575 3267 57182 15042 1066366237
7306 50822 21854 1507 38400 26758 2100784455
25339 27693 38569 18384 51023 7760 1180052548
53016 24488 48840 10551 31460 14949 2007277539
44401 48871 33387 49358 56269 34767 548338701
30550 44826 33666 53843 2237 9028 2124904168
m = twister(0) define a seed = 0. That's just for comparison. Usually it's better to initialize the generators without params. m = twister() call a seed tonumber(tostring(os.time()):reverse():sub(1,10)) (thanks, slime)
There is only needed to define a seed when choosing the LCG params, as in l3 = lcg(0, 'mvc'). After that call l3:randomseed()
:random() works the same way you're used to, except that twister:random(0) return the original 32 bits integer.
:randomseed(s) to change seed. Again, randomseed() call a nice os.time seed
Many thanks to the LuaBit Author
Edit: After some tests I found that the lcg was giving incredible bad values, because I was using all 32 bits. That won't work. Now lgc return a much better 16 bits value. random(0) to get that value, as with Twister.
Edit: v0.2 with Multiply-with-carry http://en.wikipedia.org/wiki/Multiply-with-carry
n = mwc(seed)
The rest is the same. mwc:random(0) return a 16 bit random.
Edit: v0.3 - Code optimizations. Faster.
Edit:v0.3.1 - some time for testing. Fixed Twister. Love file for testers.