Skip to content

Instantly share code, notes, and snippets.

@resuna
Last active February 25, 2018 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save resuna/a03f587676e1e8ba0d0705f401f0faea to your computer and use it in GitHub Desktop.
Save resuna/a03f587676e1e8ba0d0705f401f0faea to your computer and use it in GitHub Desktop.
import Cocoa
// *Really* minimal PCG32 code / (c) 2014 M.E. O'Neill / pcg-random.org
// Licensed under Apache License 2.0 (NO WARRANTY, etc. see website)
// Converted to Swift by Peter da Silva, backing out some C optimizations
// and hardcoding Knuth's LCG parameters
class pcg32_random {
var state: UInt64;
init(seed: UInt64 = 0)
{
state = seed
}
func next() -> UInt32
{
// Advance internal state, Knuth's mixed LCG
state = state &* 6364136223846793005 &+ 1442695040888963407;
// Calculate output function (XSH RR)
let xorshifted = UInt32(truncatingBitPattern: ((state >> 18) ^ state) >> 27);
let rot = UInt32(truncatingBitPattern: state >> 59);
return (xorshifted >> rot) | (xorshifted << UInt32((-Int32(rot)) & 31));
}
}
@irskep
Copy link

irskep commented Feb 25, 2018

For anyone else googling for this: there are a couple of mistakes. Here is the C function it implements: https://github.com/imneme/pcg-c-basic/blob/master/pcg_basic.c#L60

Note how it ignores the inc/seq value in the algorithm, and doesn't correctly use the value of state after mutating it.

@irskep
Copy link

irskep commented Feb 25, 2018

I wrote a correct version and tested it against the C library: https://gist.github.com/irskep/3a5d6cd75f4a384afff01cf742acf5be

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment