Skip to content

Instantly share code, notes, and snippets.

@keithkml
Created May 2, 2017 18:38
Show Gist options
  • Save keithkml/f92f5e7337f272a0b012745440cc6111 to your computer and use it in GitHub Desktop.
Save keithkml/f92f5e7337f272a0b012745440cc6111 to your computer and use it in GitHub Desktop.
Fast random number generator
/**
* An extremely fast pseudorandom number generator. Note that we are using
* this class to REPLACE Math.random :)
*
* Thanks to Doug Lea for help with this :)
*/
export class FastRandom {
private next;
/**
* Creates a new random number generator with the given seed, or the current
* time if no seed given.
*
* @param seed a number, or null/undefined to use the current time
*/
constructor(seed : number = undefined) {
this.seed(seed);
}
/**
* Resets this random number generator with the given seed, or the current
* time if no seed given.
*
* @param seed a number, or null/undefined to use the current time
*/
seed(seed : number = undefined) {
if (typeof seed === "undefined")
seed = new Date().getTime();
var next = seed;
next ^= (next << 6);
next ^= (next >>> 21);
next ^= (next << 7);
this.next = next;
}
/**
* Returns the next pseudorandom number in this sequence.
*
* @returns {number} a float from 0 (inclusive) to 1 (exclusive)
*/
nextFloat() {
var ret = this.next;
this.next ^= (this.next << 6);
this.next ^= (this.next >>> 21);
this.next ^= (this.next << 7);
return (ret >>> 8) / (1 << 24);
}
}
(function() {
var rng = new FastRandom();
Math["seedrandom"] = function(seed : number = undefined) {
rng.seed(seed);
};
Math.random = function() {
return rng.nextFloat()
};
rng.seed();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment