doubingqi5829 2018-06-19 00:24

# PHP伪随机数生成器

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). I have translated my javascript code in PHP but it does not work as expected. 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. I think this is because of PHP's different floating point precision but I am confused by the negative numbers.

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?

Javascript

``````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

``````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));
}
}
``````
• 写回答

#### 1条回答默认 最新

• doujia2463 2018-06-19 02:06
关注

Got it! With these numbers it works both in javascript and in 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.

I found this version in the answer to this question: Was there a a time when PHP's rand() function was used as an exploit?

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 询问MYSQL查询SQLSERVER数据表并比较差异后，更新MYSQL的数据表
• ¥15 关于#前端#的问题，请各位专家解答！
• ¥15 最小生成树问题 Prim算法和Kruskal算法
• ¥25 医院住院病人呼叫器设计
• ¥15 不想和现在的团队合作了，怎么避免他们对程序动手脚
• ¥20 C语言字符串不区分大小写字典排序相关问题
• ¥15 关于#python#的问题：我希望通过逆向技术爬取1688搜索页下滑加载的数据
• ¥15 关于Linux的终端里，模拟实现一个带口令保护的屏保程序遇到的输入输出的问题！(语言-c语言)
• ¥30 请问，这个嵌入式Linux系统谁能帮我分析一下，crc检验区域在哪，不是内核的校验，内核校验我已经找到了
• ¥15 二分类改为多分类问题