简体   繁体   English

PHP伪随机数生成器

[英]PHP pseudo random numbers generator

I am using a linear conguential generator in my javascript code but now I need to validate the results server side (generate the same numbers from the same seed). 我在JavaScript代码中使用了线性配置生成器,但是现在我需要验证结果服务器端(从同一种子生成相同的数字)。 I have translated my javascript code in PHP but it does not work as expected. 我已经用PHP翻译了我的javascript代码,但是无法正常工作。 The first few numbers are close to the javascript ones but with less precision and the sequence contains some negative numbers which are not present in the javascript version. 前几个数字与javascript的数字非常接近,但精度较低,并且该序列包含一些在javascript版本中不存在的负数。 I think this is because of PHP's different floating point precision but I am confused by the negative numbers. 我认为这是因为PHP的浮点精度不同,但是我对负数感到困惑。

If there is no easy way to make this work in PHP what other methods could I use to generate the same sequence of pseudo-random numbers both in javascript and in PHP? 如果没有简单的方法可以在PHP中实现此功能,那么我还可以使用其他什么方法在javascript和PHP中生成相同的伪随机数序列?

Javascript Java脚本

function SeededRandom(newSeed) {
    this.seed = newSeed;
    this.Random = function (min, max) {
        this.seed = (this.seed * 9301 + 49297) % 233280;
        return Math.floor(min + (this.seed / 233280) * (max - min + 1));
    }
}

PHP 的PHP

class SeededRandom {
    private $seed;
    public function __construct($newSeed) {
        $this->seed = $newSeed;
    }
    public function Random($min, $max) {
        $this->seed = ($this->seed * 9301 + 49297) % 233280;
        return floor($min + ($this->seed / 233280) * ($max - $min + 1));
    }
}

Got it! 得到它了! With these numbers it works both in javascript and in PHP. 有了这些数字,它就可以在javascript和PHP中使用。

function SeededRandom2(newSeed) {
    this.seed = newSeed;
    this.Random = function () {
        this.seed = (this.seed * 20077 + 12345) % 32768;
        return this.seed;
    }
}

The negative numbers were probably caused by integer overflow and the divergence between the javascript and PHP numbers was caused by the division. 负数可能是整数溢出引起的,而javascript和PHP数字之间的差异是由除法引起的。

I found this version in the answer to this question: Was there aa time when PHP's rand() function was used as an exploit? 我在以下问题的答案中找到了此版本: 是否有一段时间将PHP的rand()函数用作漏洞利用程序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM