Skip to content

Instantly share code, notes, and snippets.

@oov
Created May 11, 2012 10:18
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 oov/2658770 to your computer and use it in GitHub Desktop.
Save oov/2658770 to your computer and use it in GitHub Desktop.
XorShiftRNG
XorShiftRNG = (function(){
//from: http://d.hatena.ne.jp/uupaa/20091223/1261528727
var nowimpl = !!Date.now;
//from: http://homepage2.nifty.com/magicant/sjavascript/mt.html
function mul(a, b) {
var a1 = a >>> 16, a2 = a & 0xffff;
var b1 = b >>> 16, b2 = b & 0xffff;
return (((a1 * b2 + a2 * b1) << 16) + a2 * b2) >>> 0;
}
function XorShiftRNG(seed){
if (arguments.length == 0){
this.setSeedByTime();
} else {
this.setSeed(seed);
}
}
XorShiftRNG.prototype.setSeedByTime = function(){
this.setSeed(nowimpl ? Date.now() : +new Date());
}
//from: http://unkar.org/r/tech/1192628099#l75
XorShiftRNG.prototype.setSeed = function(seed){
var x = 1812433253;
this._x = seed = mul(x, (seed^(seed>>>30)))+1;
this._y = seed = mul(x, (seed^(seed>>>30)))+2;
this._z = seed = mul(x, (seed^(seed>>>30)))+3;
this._w = seed = mul(x, (seed^(seed>>>30)))+4;
}
XorShiftRNG.prototype.next = function(){
return this.nextUInt32() / 4294967295;
}
XorShiftRNG.prototype.nextUInt32 = function(){
var w = this._w, t = this._x ^ (this._x << 11);
this._x = this._y;
this._y = this._z;
this._z = w;
return this._w = ((w ^ w >>> 19) ^ (t ^ t >>> 8)) >>> 0;
}
return XorShiftRNG;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment