Skip to content

Instantly share code, notes, and snippets.

@toji
Created June 15, 2012 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save toji/2937842 to your computer and use it in GitHub Desktop.
Save toji/2937842 to your computer and use it in GitHub Desktop.
Simple Javascript implementation of CMWC Psuedorandom algorithm
// This was basically ripped straight from http://en.wikipedia.org/wiki/Multiply-with-carry, just javscriptified.
var CMWCRand = function(seed) {
var i, PHI = 0x9e3779b9;
if(!seed) { seed = Date.now(); }
var Q = this.Q = new Uint32Array(4096);
this.c = 362436;
this.i = 4095;
Q[0] = seed;
Q[1] = seed + PHI;
Q[2] = seed + PHI + PHI;
for(i = 3; i < 4096; ++i) {
Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i;
}
};
CMWCRand.prototype.randomUInt32 = function() {
var Q = this.Q;
var t, a = 18782;
var x, r = 0xfffffffe;
this.i = (this.i + 1) & 4095;
t = a * Q[this.i] + this.c;
this.c = (t >> 32);
x = t + this.c;
if (x < this.c) {
x++;
this.c++;
}
return (Q[this.i] = r - x);
};
var randRange = 1.0/0xffffffff;
CMWCRand.prototype.random = function() {
return this.randomUInt32() * randRange;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment