scala和cpp中的以下代码生成一个相同的随机数序列。我试图用php编写等价的代码,但遇到了一些困难。
class Rand {
long int seed;
public:
Rand(long int _seed) {
seed = _seed;
}
int next(int bits) {
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
return (seed >> (48 - bits));
}
int nextInt() {
return next(32);
}
};
斯卡拉:
class Random(initialSeed: Long) {
var seed: Long = initialSeed
def setSeed(s: Long): Unit = {
seed = s
}
def next(bits: Int): Int = {
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
(seed >>> (48 - bits)).toInt
}
def nextInt() = next(32)
}
到目前为止,在php中我有以下几点,但还远远不够。我认为主要的困难是模拟cpp和scala/java能够显式执行的32位和64位整数。
<?php
class Rand {
protected $rseed;
function __construct($s) {
$rseed = $s;
}
public function rnext($bits) {
$a = ($this->rseed * 0x5DEECE66D + 0xB);
$b = (1 << 48) - 1;
$this->rseed = $a & $b;
// implementation note - in JAVA the next line has >>> not >> which does a zero fill of the shifted
// value which probably is important and must be simulated in PHP
$ret = ($this->rseed >> (48 - $bits));
return $ret;
}
public function nextInt() {
return $this->rnext(32);
}
}
$r = new Rand(916916916);
echo "rand " . $r->nextInt();
最佳答案
我认为像gmp这样的图书馆可能是答案。这是一次尝试,不确定是否
它是正确的,可能可以清理一点…
class Rand {
protected $rseed;
private $mul;
private $add;
function __construct($s) {
$this->rseed = $s;
$this->mul = gmp_init(0x5DEECE66D);
$this->add = gmp_init(0xB);
}
public function rnext($bits) {
$a = gmp_add(gmp_mul(gmp_init($this->rseed), $this->mul), $this->add);
$aInt = gmp_intval(gmp_mod($a, gmp_init(PHP_INT_MAX)));
$b = (1 << 48) - 1;
$this->rseed = $aInt & $b;
$ret = ($this->rseed >> (48 - $bits));
return $ret;
}
public function nextInt() {
return $this->rnext(32);
}
}
$r = new Rand(916916916);
echo "rand " . $r->nextInt();
关于java - 在PHP中实现以下随机生成器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25510704/