PHP 相当于 javascript Math.random()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17690165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP equivalent of javascript Math.random()
提问by Mateusz Bi?gorajski
I need a PHP function that generates random number identical to javascript Math.random() with the same seed.
我需要一个 PHP 函数,它生成与具有相同种子的 javascript Math.random() 相同的随机数。
MDN about math.random():
关于 math.random() 的 MDN:
The random number generator is seeded from the current time, as in Java.
随机数生成器从当前时间开始,就像在 Java 中一样。
As far I tried the PHP's rand() generates something like that:
到目前为止,我尝试过 PHP 的 rand() 生成类似的东西:
srand( time() ); // I use time as seed, like javascript does
echo rand();
Output: 827382
And javascript seems to generate random numbers on it's own way:
并且 javascript 似乎以自己的方式生成随机数:
Math.random(); Output: 0.802392144203139
I need PHP code that is equivalent for math.random(), not new javascript code. I can't change javascript.
我需要与 math.random() 等效的 PHP 代码,而不是新的 javascript 代码。我无法更改 javascript。
回答by thiagobraga
You could use a function that returns the value:
您可以使用返回值的函数:
PHP
PHP
function random() {
return (float)rand()/(float)getrandmax();
}
// Generates
// 0.85552537614063
// 0.23554185613575
// 0.025269325846126
// 0.016418958098086
JavaScript
JavaScript
var random = function () {
return Math.random();
};
// Generates
// 0.6855146484449506
// 0.910828611580655
// 0.46277225855737925
// 0.6367355801630765
@elclanrs solution is easier and doesn't need the cast in return.
@elclanrs 解决方案更简单,不需要演员表作为回报。
Update
更新
There's a good question about the difference between PHP mt_rand()
and rand()
here:
What's the disadvantage of mt_rand?
关于 PHPmt_rand()
和rand()
这里的区别有一个很好的问题:
mt_rand 的缺点是什么?
回答by Carlos Llongo
Javascript's Math.random gives a random number between 0 and 1. Zero is a correct output, but 1 should not be included. @thiagobraga's answer could give 1 as an output. My solution is this:
Javascript 的 Math.random 给出一个介于 0 和 1 之间的随机数。零是正确的输出,但不应包括 1。@thiagobraga 的回答可以给出 1 作为输出。我的解决方案是这样的:
function random(){
return mt_rand() / (mt_getrandmax() + 1);
}
This will give a random number between 0 and 0.99999999953434.
这将给出一个介于 0 和 0.99999999953434 之间的随机数。
回答by Shawn31313
You could try:
你可以试试:
function random () {
return (float)("0." . rand(1e15, 999999999999999));
}
Or even:
甚至:
function random () {
return rand(1e15, 999999999999999) / 1e15;
}
However, @elclanrs solution seems a lot easier. I tried.
但是,@elclanrs 解决方案似乎要容易得多。我试过。