PHP相当于javascript Math.random() [英] PHP equivalent of javascript Math.random()
问题描述
我需要一个PHP函数,它生成与javascript Math.random()
width相同种子的随机数。
I need a PHP function that generate random number identical to javascript Math.random() width the same seed.
关于math.random()的MDN:
MDN about math.random():
随机数生成器是从当前时间播种,如
Java。
The random number generator is seeded from the current time, as in Java.
到目前为止,我尝试了PHP的rand()生成类似的东西:
As far I tried the PHP's rand() generates something like that:
srand( time() ); // I use time as seed, like javascript does
echo rand();
Output: 827382
javascript似乎以自己的方式生成随机数:
And javascript seems to generate random numbers on it's own way:
Math.random(); Output: 0.802392144203139
我需要与math.random()等效的PHP代码,而不是新的javascript代码。我无法更改javascript。
I need PHP code that is equivalent for math.random(), not new javascript code. I can't change javascript.
推荐答案
您可以使用返回值的函数:
You could use a function that returns the value:
function random() {
return (float)rand()/(float)getrandmax();
}
// Generates
// 0.85552537614063
// 0.23554185613575
// 0.025269325846126
// 0.016418958098086
var random = function () {
return Math.random();
};
// Generates
// 0.6855146484449506
// 0.910828611580655
// 0.46277225855737925
// 0.6367355801630765
@elclanrs解决方案更容易,不需要演员回报。
@elclanrs solution is easier and doesn't need the cast in return.
更新
关于PHP mt_rand()$之间的区别有一个很好的问题c $ c>和
rand()
这里:
mt_rand的缺点是什么?
There's a good question about the difference between PHP mt_rand()
and rand()
here:
What's the disadvantage of mt_rand?
这篇关于PHP相当于javascript Math.random()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!