我正在寻找一种将0和1之间的浮点值转换为数组索引的方法.
其思想是基于浮点概率值随机选取数组元素.我想出了下面的代码,它try 这样做1000次.然后跟踪在$Counts数组中 Select 每个值的频率.
Get_rand_index_1()函数使用ROUND(),$count-1.这里的问题是,第一个和最后一个索引,在本例中是0/Apple和5/菠萝,被选中的频率只有原来的一半.导致$计算的结果类似于:
Array
(
[Apples] => 142
[Oranges] => 236
[Bananas] => 269
[Pineapples] => 104
[Pears] => 249
)
我还编写了get_rand_index_2().它使用FLOOR()而不是ROUND(),使用$count代替($count-1).我认为这可以解决问题,但如果浮点数为1,则会出现问题.在这种情况下,索引将无效.当然,这是极不可能的,但在理论上仍是可能的.如果一次生成数百万个随机值,可能会出现问题.
所以我做了减go 1/mt_getrandmax().然后在极少数情况下将数字变为负数,我使用max(0,...).
我认为这个get_rand_index_2()起作用了,得到的$Counts数组似乎具有完全分布的值.但这似乎有点老生常谈.我也不确定这是不是最有效的方式.
有没有更优雅或更有效的方式来做我想要的事情?
以下是我正在测试的代码.
<?php
$array = ["Apples", "Bananas", "Oranges", "Pears", "Pineapples"];
$count = count($array);
$counts = [];
for ($i = 0; $i < 1000; $i++) {
//$index = get_rand_index_1($count);
$index = get_rand_index_2($count);
$value = $array[$index];
if (!isset($counts[$value])) $counts[$value] = 1;
else $counts[$value]++;
}
print_r($counts);
function get_rand_index_1(int $count)
{
$float_rand = mt_rand() / mt_getrandmax();
$index = round($float_rand * ($count - 1));
return $index;
}
function get_rand_index_2(int $count)
{
$float_rand = max(0, mt_rand() / mt_getrandmax() - 1 / mt_getrandmax());
$index = floor($float_rand * $count);
return $index;
}