GLBasic forum

Codesnippets => Inline / 3rd party => Topic started by: Wampus on 2012-Feb-15

Title: Extremely simple and fast XorShift randomizer
Post by: Wampus on 2012-Feb-15
The code below creates medium quality pseudorandom numbers using Xorshift. With better quality pseudorandom number generation that is almost as fast the Mersenne Twister (http://www.glbasic.com/forum/index.php?topic=2821) code found on this forum would be a better choice for most tasks. I thought I'd post this Xorshift code anyway.

XorShiftSeed(num) - Sets the Xorshift randomizer with seed num.

XorShift(maxnum) - Generates a random number with the range 0 to maxnum-1.

Code (glbasic) Select
INLINE

static unsigned long xxs=123456789, yxs=362436069, zxs=521288629;

unsigned long xorshrseed(unsigned long int SeedNumXS) {
xxs = SeedNumXS, yxs=362436069, zxs=521288629;
}

unsigned long xorshf(unsigned long int mmaxNumXS) {       
unsigned long txs;
xxs ^= xxs << 21;
xxs ^= xxs >> 35;
xxs ^= xxs << 4;

txs = xxs;
xxs = yxs;
yxs = zxs;
zxs = txs ^ xxs ^ yxs;

return (zxs % mmaxNumXS);
}

ENDINLINE



FUNCTION XorShiftSeed: snum

INLINE
xorshrseed((unsigned long) snum);
ENDINLINE

ENDFUNCTION



FUNCTION XorShift: mnum

INLINE
return xorshf((unsigned long) mnum);
ENDINLINE

ENDFUNCTION