I don't have access to random() in Lua 4.0 (DON'T ASK), so I need to roll my own random number generator. Or rather I have to roll another one since the one I implemented several years ago is failing me now. I.e. I am noticing repeating values which is bad.
Any suggestions or examples written in Lua that I can use? FYI here's the one I've been using up until now:
seedobja = 1103515245
seedobjc = 12345
seedobjm = 4294967295 --0x100000000
function srandom(seedobj, fVal1, fVal2)
seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
local temp_rand = seedobj[1] / (seedobjm - 1)
if (fVal2) then
return floor(fVal1 + 0.5 + temp_rand * (fVal2 - fVal1))
elseif (fVal1) then
return floor(temp_rand * fVal1) + 1
else
return temp_rand
end
end
[edit]
Later edit deleted.
I have not Lua 4.0 installed and never worked with it, thus the following code may need some tweaks.
This is something that works on Lua 5.1. It is a rough adaptation of an implementation of the Park and Miller generator (written in C, using 32 bit ints). I tried to come closer to the 4.0 syntax (that I guessed from your snippet). Test it and see if its period suits your needs. The original version has a period of about
2e9
, but converting to float arithmetic may have broken something (these generators are delicate things).I've found a solution here:
I don't know about the statistical properties, but the function is not returning duplicate values even after many thousands of iterations. Thanks for everyone's help regardless!
Here is another attempt (always Lua 5.1 code), using an adaptation from C of a subtractive generator by Knuth (not linear congruential then). According to Knuth it should work with FP arithmetic (even single precision).