RanRot/b PNRG: Translation from C to Lua : weirdo...
Posted: Mon Jan 06, 2014 5:15 pm
Hi all,
Disclaimer: I am fairly inexperienced to C (and bitwise ops), apologies in advance if I am saying silly things.
Well, I was trying to translate to Lua the following C-code which is supposed to be a RANROT/B PRNG:
Well, Lua 5.2 has bitwise ops, therefore I went with it. I added DavidManura's numberlua, in order to have compatible bitwise ops for Lua 5.1.4, or LuaJit:
(note, you can run it with the online cgi-bin Lua demo (5.2)
Then I tested it this way:
The output is just ... strange. The first 20-30 values seems to be quite good, actually, then after that, I get a tons of 0's...
Can anyone explain and give pointers on how to fix that ?
Thanks in advance.
Disclaimer: I am fairly inexperienced to C (and bitwise ops), apologies in advance if I am saying silly things.
Well, I was trying to translate to Lua the following C-code which is supposed to be a RANROT/B PRNG:
Code: Select all
/*
RANROT-B/32 PRNG
Call with 1 or higher to set seed; call with 0 to fetch values.
Robin Leffmann 2005 / <robin at stolendata dot net>
*/
#include <stdint.h>
static uint32_t rrbRand( uint32_t rrbSeed )
{
static uint32_t rrbLo, rrbHi;
if( rrbSeed != 0 )
{
rrbLo = rrbSeed;
rrbHi = ~rrbSeed;
}
else
{
rrbHi = ( rrbHi << 16 ) + ( rrbHi >> 16 );
rrbHi += rrbLo;
rrbLo += rrbHi;
}
return rrbHi;
}
(note, you can run it with the online cgi-bin Lua demo (5.2)
Code: Select all
local function checkBitImplementation(bit)
local msg = 'Failed testing bitwise implementation'
assert(bit.bnot ~= nil, msg)
assert(bit.lshift ~= nil, msg)
assert(bit.rshift ~= nil, msg)
assert(bit.bnot(0) == 4294967295, msg)
assert(bit.lshift(2, 16) == 131072, msg)
assert(bit.rshift(2, 16) == 0, msg)
return bit
end
local bit = checkBitImplementation(
_VERSION:match('5.2') and bit32
or (jit ~= nil) and require ('numberlua').bit
or require 'numberlua'
)
-- Returns an iterator function
local function ranrotb(seed)
seed = seed or os.time()
local lo, hi = seed, bit.bnot(seed)
return function()
hi = bit.lshift(hi,16) + bit.rshift(hi, 16)
hi = hi + lo
lo = lo + hi
return hi
end
end
Code: Select all
-- Generates n random numbers betwen 1 and max
local function gen(n, max)
local prng = ranrotb()
local t = {}
for i = 1, n do t[#t+1] = (prng() % max) end
return t
end
-- Generates and print 100 random numbers between 1 and 10.
print(table.concat(gen(100, 10),'\n'))
Can anyone explain and give pointers on how to fix that ?
Thanks in advance.