-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrng32jit.lua
More file actions
44 lines (37 loc) · 952 Bytes
/
rng32jit.lua
File metadata and controls
44 lines (37 loc) · 952 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
local bit = require("bit")
local function xorshift(x)
-- x = (x ~ x << 13) & 2147483647
-- x = (x ~ x >> 17) & 2147483647
-- x = (x ~ x << 5) & 2147483647
x = bit.band(bit.bxor(x, bit.lshift(x, 13)), 2147483647)
x = bit.band(bit.bxor(x, bit.rshift(x, 17)), 2147483647)
x = bit.band(bit.bxor(x, bit.lshift(x, 5)), 2147483647)
return x
end
local RNG = {}
RNG.__index = RNG
function RNG.new(seed)
local self = setmetatable({}, RNG)
self:seed(seed or 1)
return self
end
function RNG:seed(seed)
-- self.state = (seed * 23456789) & 2147483647
self.state = bit.band(seed * 23456789, 2147483647)
end
function RNG:next()
local x = xorshift(self.state)
self.state = x
return x
end
function RNG:random(a, b)
local x = self:next()
if not a then
return x / 2147483647
elseif not b then
return x % a + 1
else
return x % (b - a + 1) + a
end
end
return RNG