Created
May 19, 2016 23:57
-
-
Save Kcazer/c8f6d53951b77ca5e12b79585979a05c to your computer and use it in GitHub Desktop.
Simple implementation of MT19937
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MT19937 { | |
protected $state = []; | |
protected $index = 624; | |
public function __construct($seed = null) { | |
$this->state[0] = ($seed === null ? 5489 : $seed); | |
for ($i = 1; $i < 624; $i++) { | |
$this->state[$i] = (0x6C078965 * ($this->state[$i - 1] ^ ($this->state[$i - 1] >> 30)) + $i) & 0xffffffff; | |
} | |
} | |
public function int32() { | |
if ($this->index == 624) { | |
$this->index = 0; | |
for ($i = 0; $i < 227; $i++) { | |
$y = ($this->state[$i] & 0x80000000) | ($this->state[$i + 1] & 0x7fffffff); | |
$this->state[$i] = $this->state[$i + 397] ^ (($y >> 1) & 0x7fffffff) ^ (0x9908b0df * ($y & 1)); | |
} | |
for (; $i < 623; $i++) { | |
$y = ($this->state[$i] & 0x80000000) | ($this->state[$i + 1] & 0x7fffffff); | |
$this->state[$i] = $this->state[$i - 227] ^ (($y >> 1) & 0x7fffffff) ^ (0x9908b0df * ($y & 1)); | |
} | |
$y = ($this->state[623] & 0x80000000) | ($this->state[0] & 0x7fffffff); | |
$this->state[623] = $this->state[396] ^ (($y >> 1) & 0x7fffffff) ^ (0x9908b0df * ($y & 1)); | |
} | |
$y = $this->state[$this->index++]; | |
$y ^= ($y >> 11) & 0x001fffff; | |
$y ^= ($y << 7) & 0x9d2c5680; | |
$y ^= ($y << 15) & 0xefc60000; | |
$y ^= ($y >> 18) & 0x00003fff; | |
return $y; | |
} | |
public function int16() { | |
return $this->int32() & 0xFFFF; | |
} | |
public function int8() { | |
return $this->int32() & 0xFF; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment