Skip to content

Instantly share code, notes, and snippets.

@nicoptere
Last active February 6, 2020 08:32
Show Gist options
  • Save nicoptere/fa5165d37a2902736eeb to your computer and use it in GitHub Desktop.
Save nicoptere/fa5165d37a2902736eeb to your computer and use it in GitHub Desktop.
Mersenne Twister: a good Pseudo Random Number Generator ( PRNG )
/*
from : http://en.wikipedia.org/wiki/Mersenne_twister
*/
let MT
let index
class PRNG {
static setSeed(seed) {
// Create a length 624 array to store the state of the generator
MT = new Uint32Array(624)
index = 0
MT[0] = seed
for (let i = 1; i < 624; i++) {
MT[i] = 1812433253 * (MT[i - 1] ^ ((MT[i - 1] >> 30) + i))
}
}
static extractNumber() {
if (index === 0) {
this.generateNumbers()
}
let y = MT[index]
y = y ^ (y >> 11)
y = y ^ ((y << 7) & 2636928640)
y = y ^ ((y << 15) & 4022730752)
y = y ^ (y >> 18)
index = (index + 1) % 624
return y
}
static generateNumbers() {
for (let i = 0; i < 624; i++) {
const y = (MT[i] & 0x80000000) + (MT[(i + 1) % 624] & 0x7fffffff)
MT[i] = MT[(i + 397) % 624] ^ (y >> 1)
if (y % 2 !== 0) {
MT[i] = MT[i] ^ 2567483615
}
}
}
static random() {
return this.extractNumber() / 0x7fffffff
}
}
PRNG.setSeed(1)
export default PRNG
/*
//usage:
PRNG.setSeed( seed );//seed: any int, uint or number
PRNG.random(); //returns a pseudo-random value between 0 & 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment