【发布时间】:2014-03-17 23:41:13
【问题描述】:
几何平均值的基本计算并不难,但我发现自己遇到了 INF,因为数字列表很大,最多 10k。所以我尝试记录数字并稍后取幂,但我仍然得到 INF。
下一步是对数字数组进行分块,这看起来不错,但是现在我有一个问题,如果有分块数组的提醒,结果会出错。这条路上有什么解决方案,还是您更喜欢其他计算几何平均值的方法?
# 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));
}
【问题讨论】:
-
如果你想要替代解决方案,你应该添加你需要的几何平均值。
-
你是如何记录日志的?你试过exponentiate the arithmetic mean of logarithms吗?
-
我通过为 $a 上的每个项目获取 log($i) 然后 exp(_geometric_mean($a)) 来做到这一点。但是您的链接(我之前访问过它,但没有看到该部分)给了我最终的解决方案。你可以在我自己的决议上看到它。感谢您指出这一点@ragol!