Skip to content

Instantly share code, notes, and snippets.

@nicoptere

nicoptere/PRNG

Last active Feb 6, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.