几何平均值的基本计算并不困难,但我发现自己打了INF,因为数字列表很大,高达10k。所以我试着记录数字并稍后取指数,但我仍然得到了INF。
接下来的步骤是数字数组,这似乎很好,但现在我有一个问题,如果有一个chunked数组的提醒,结果将是错误的。在这条路上有没有解决方案,或者你更喜欢其他一些计算几何平均值的方法?
# testing with small number set
$a = array(13, 18, 13, 14, 13, 16, 14, 21, 13);
# number set will splice uneven with 2, thus giving wrong answer?
echo geometric_mean($a, 2);
echo " wrong<br />";
# number set will chunk evenly to 3 parts, thus giving right answer
echo geometric_mean($a, 3);
echo " correct<br />";
# straight way without splitting
echo _geometric_mean($a);
echo " correct<br />";
function geometric_mean($a, $size = 20) {
$a = array_chunk($a, $size);
foreach ($a as $b) {
# finding, if there is a reminder after split of an array
$c = count($b);
if ($c < $size) {
for ($i=$c; $i<$size; $i++) {
# adding last mean to the array, but it's not good
# adding 14.789726414533 would be ok...
$b[] = $m;
}
}
$m = _geometric_mean($b);
$d[] = $m;
}
# recursive call if array size is bigger
if (count($d) > $size) {
geometric_mean($d, $size);
}
return _geometric_mean($d);
}
# basic function to get geometric mean
function _geometric_mean($a) {
return pow(array_product($a), 1 / count($a));
}
答案 0 :(得分:2)
解决方案的灵感来源于:http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms由@ragol带来:
function geometric_mean($a) {
array_walk($a, function (&$i) {
$i = log($i);
});
return exp(array_sum($a)/count($a));
}
我不确定效率,但它在我的应用程序上运行良好,不需要数组拼接,重复函数调用,仍然不再有INF。
答案 1 :(得分:0)
该错误意味着该数字对于内存来说太大了。当你试图回应它时,可能会出现问题。我不太确定。尝试使用此功能:
is_infinite()