Skip to content

Instantly share code, notes, and snippets.

@cstorey
Created March 1, 2014 23:35
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 cstorey/9299360 to your computer and use it in GitHub Desktop.
Save cstorey/9299360 to your computer and use it in GitHub Desktop.
Pseudorandom number generator in Javascript. Algorithm from "Fast and Small Nonlinear Pseudorandom Number Generators for Computer Simulation" by Samuel Neves and Filipe Araujo.
function Tyche(seed, idx) {
this.a = seed & 0xffffffff;
this.b = (seed / ((2<<16)*(2<<16))) & 0xffffffff;
this.c = 2654435769;
this.d = (1367130551 ^ idx) >>> 0;
for (var i = 20; i > 0; --i) {
this._mix();
}
}
function rot(x, n) {
return (x << n | x >>> (32 - n | 0)) >>> 0;
}
Tyche.prototype._mix = function _mix() {
this.a = (this.a + this.b | 0) >>> 0;
this.d = rot(this.d ^ this.a, 16);
this.c = (this.c + this.d | 0) >>> 0;
this.b = rot(this.b ^ this.c, 12);
this.a = (this.a + this.b | 0) >>> 0;
this.d = rot(this.d ^ this.a, 8);
this.c = (this.c + this.d | 0) >>> 0;
this.b = rot(this.b ^ this.c, 7);
}
Tyche.prototype.next = function next() {
this._mix();
return this.b;
}
function test(ntimes) {
var t = new Tyche(0,0);
var d0 = new Date();
for (var i = ntimes; i != 0; --i) {
t.next()
};
var d1 = new Date();
console.log(t.next());
console.log(ntimes + " iterations " + (d1-d0) + "ms");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment