問(wèn)題描述
我正在尋找一種使用 PHP 生成大隨機(jī)數(shù)的方法,例如:
I'm looking for a way to generate a big random number with PHP, something like:
mt_rand($lower, $upper);
我見(jiàn)過(guò)的更接近的是 gmp_random() 但是它不允許我僅指定每個(gè)肢體的位數(shù)(我不知道它是什么).
The closer I've seen is gmp_random() however it doesn't allow me to specify the lower and upper boundaries only the number of bits per limb (which I've no idea what it is).
Axsuuls 的答案似乎非常接近我想要的并且與 gmp_random 非常相似,但是在一種情況下似乎只有一個(gè)缺陷.
假設(shè)我不想在兩者之間得到一個(gè)隨機(jī)數(shù):
Suppose I wan't to get a random number between:
- 1225468798745475454898787465154
和:
- 1225468798745475454898787465200
所以如果函數(shù)被調(diào)用BigRandomNumber():
So if the function is called BigRandomNumber():
BigRandomNumber($length = 31);
這很容易返回超出指定邊界的 9999999999999999999999999999999.
This can easily return 9999999999999999999999999999999 which is out of the specified boundary.
如何使用最小/最大邊界而不是長(zhǎng)度值?
BigRandomNumber('1225468798745475454898787465154', '1225468798745475454898787465200');
這應(yīng)該返回 1225468798745475454898787465 [154 .. 200] 之間的隨機(jī)數(shù).
This should return a random number between 1225468798745475454898787465 [154 .. 200].
作為參考,我認(rèn)為解決方案可能必須使用 此問(wèn)題中提供的函數(shù).
For the reference I believe the solution might have to make use of the function supplied in this question.
上面的帖子被刪除了,這里是:
The above post was deleted, here it is:
function compare($number1, $operator, $number2) {
$x = bccomp($number1, $number2);
switch($operator) {
case '<':
return -1===$x;
case '>':
return 1===$x;
case '=':
case '==':
case '===':
return 0===$x;
case '!=':
case '!==':
case '<>':
return 0!==$x;
}
}
推薦答案
嘗試以下操作:
function BigRandomNumber($min, $max) {
$difference = bcadd(bcsub($max,$min),1);
$rand_percent = bcdiv(mt_rand(), mt_getrandmax(), 8); // 0 - 1.0
return bcadd($min, bcmul($difference, $rand_percent, 8), 0);
}
數(shù)學(xué)如下:將最小值和最大值之間的差值乘以一個(gè)隨機(jī)百分比,然后加上最小值(四舍五入為整數(shù)).
The math is as following: multiply the difference between the minimum and maximum by a random percentage, and add to the minimum (with rounding to an int).
這篇關(guān)于在 PHP 中,如何生成一個(gè)大的偽隨機(jī)數(shù)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!