我有以下数组:
public $percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 );//它总和为100%
我需要一个随机函数来返回键值的百分比,
例如:得到0的可能性是20.30%,得到2的可能性是14.15%,第一个用户得到0,第二个得到2。
请让我知道你建议我使用的功能是什么。
i have the following array:
public $percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 );// it sums in 100%
I need a random function to return the key by the percentage of the value,
for example: the possibility to get 0 is 20.30% and the possibility to get 2 is 14.15%, the first user got 0, the second one got 2.
Please let me know what is the function you suggest me to use.
最满意答案
将百分比转换为累计概率,然后将其与随机数进行比较。
如果随机数属于某个类别,则输出结果。 如果没有,移动到下一个,直到找到一个。 这使您可以根据数组中陈述的概率百分比输出一个数字。
$percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 ); $random = mt_rand(0,10000)/100; foreach ($percentage as $key => $value) { $accumulate += $value; if ($random <= $accumulate) { echo $key; break; } }Convert the percentages to an accumulated probability, then compare it with a random number.
If the random number falls into a category, outputs the result. If not, move onto the next one until one is found. This allows you to output a number based on the percentage probability stated in the array.
$percentage = array( 0 => 20.30, 1=> 19.96, 2=> 14.15, 3=> 45.59 ); $random = mt_rand(0,10000)/100; foreach ($percentage as $key => $value) { $accumulate += $value; if ($random <= $accumulate) { echo $key; break; } }更多推荐
发布评论