【问题标题】:How to calculate geometric mean with big list of numbers up to four digits?如何用最多四位数的大数字列表计算几何平均值?
【发布时间】: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!

标签: php average mean


【解决方案1】:

该错误意味着数字太大而无法存储。当您尝试回应它时,可能会出现问题。我不太确定。尝试使用此功能:

is_infinite()

【讨论】:

  • 是的,它对于内存来说太大了,这就是我试图通过拆分生产数组并获得较小数字集的几何平均值来避免的。
【解决方案2】:

解决方案灵感来自:@ragol 带来的http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms

function geometric_mean($a) {
    array_walk($a, function (&$i) {
        $i = log($i);
    });
    return exp(array_sum($a)/count($a));
}

我不确定效率,但它在我的应用上运行良好,不需要数组拼接、重复函数调用,而且仍然没有更多 INF。

【讨论】:

    猜你喜欢
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多