Skip to content

Instantly share code, notes, and snippets.

@Snack-X
Created January 27, 2015 06:46
Show Gist options
  • Save Snack-X/f91b6d02fd192cbe8216 to your computer and use it in GitHub Desktop.
Save Snack-X/f91b6d02fd192cbe8216 to your computer and use it in GitHub Desktop.
pcg32 in python, see http://www.pcg-random.org/
import pcg32
# make a generator
# must seed
rng = pcg32.rng()
pcg32.srandom_r(rng, 42, 52)
for i in range(16):
print pcg32.random_r(rng)
# or use it global
# must seed
pcg32.srandom(42, 52)
for i in range(16):
print pcg32.random()
def _uint32(n):
return n & 0xffffffff
def _uint64(n):
return n & 0xffffffffffffffff
def rng(state=0, inc=0):
return {
'state': _uint64(state),
'inc': _uint64(inc)
}
_pcg32_global = rng(0x853c49e6748fea9b, 0xda3e39cb94b95bdb)
def srandom_r(rng, initstate, initseq):
initstate = _uint64(initstate)
initseq = _uint64(initseq)
rng['state'] = 0
rng['inc'] = _uint64(initseq << 1) | 1
random_r(rng)
rng['state'] = _uint64(rng['state'] + initstate)
random_r(rng)
def srandom(seed, seq):
srandom_r(_pcg32_global, seed, seq)
def random_r(rng):
oldstate = rng['state']
rng['state'] = _uint64(oldstate * 6364136223846793005 + rng['inc'])
xorshifted = _uint32(((oldstate >> 18) ^ oldstate) >> 27)
rot = _uint32(oldstate >> 59)
return _uint32((xorshifted >> rot) | (xorshifted << ((-rot) & 31)))
def random():
return random_r(_pcg32_global)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment