以下 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/