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);
}
};
Scala的:
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();
答案 0 :(得分:1)
我认为像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();