1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 | local floor = math.floor
local NORM = 2.328306549295727688e-10
local M1 = 4294967087.0
local M2 = 4294944443.0
local A12 = 1403580.0
local A13N = 810728.0
local A21 = 527612.0
local A23N = 1370589.0
local _counter = 0
local make_generator
make_generator = function(seed)
if not (seed) then
_counter = _counter + 1
seed = os.time() * 1000 + _counter + floor(os.clock() * 1000)
end
local s = { }
local x = floor(seed) % 2147483647
if x == 0 then
x = 12345
end
for i = 1, 6 do
x = (16807 * x) % 2147483647
s[i] = x
end
local s10, s11, s12 = s[1] % M1, s[2] % M1, s[3] % M1
local s20, s21, s22 = s[4] % M2, s[5] % M2, s[6] % M2
if s10 == 0 and s11 == 0 and s12 == 0 then
s10 = 1
end
if s20 == 0 and s21 == 0 and s22 == 0 then
s20 = 1
end
local next_number
next_number = function()
local p1 = A12 * s11 - A13N * s10
local k = floor(p1 / M1)
p1 = p1 - (k * M1)
if p1 < 0 then
p1 = p1 + M1
end
s10, s11, s12 = s11, s12, p1
local p2 = A21 * s22 - A23N * s20
k = floor(p2 / M2)
p2 = p2 - (k * M2)
if p2 < 0 then
p2 = p2 + M2
end
s20, s21, s22 = s21, s22, p2
if p1 <= p2 then
return (p1 - p2 + M1) * NORM
else
return (p1 - p2) * NORM
end
end
local generator = { }
generator.random = function(m, n)
if m == nil then
return 1 - next_number()
end
if n == nil then
m, n = 1, m
end
m, n = floor(m), floor(n)
if m > n then
error("bad argument to random (interval is empty)", 2)
end
return m + floor((1 - next_number()) * (n - m + 1))
end
generator.seed = function(new_seed)
local g = make_generator(new_seed)
s10, s11, s12, s20, s21, s22 = g.state()
end
generator.state = function()
return s10, s11, s12, s20, s21, s22
end
return generator
end
return {
make_generator = make_generator
}
|