如何计算加权平均值? [英] How to calculate a weighted mean?

查看:190
本文介绍了如何计算加权平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的语言是PHP,但算法应该是相当普遍的。

My language is PHP, but the algorithm should be fairly universal.

我有(比方说)评级和时代一直是等级定数的关联数组。

I have an associative array of (let's say) ratings and number of times that rating has been given.

$ratings = array(
    1 => 1,
    2 => 3,
    3 => 6,
    4 => 3,
    5 => 3
);

这是等价的: [1,2,2,2,3,3,3,3,3,3,4,4,4,5,5,5] ,但鉴于我正在与数字,这将是非常低效的,从第一形式转换为第二

This is the equivalent of: [1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5], but given the numbers I'm working with, it would be quite inefficient to convert from the first form to the second.

什么是算法来计算上面的数字的是什么意思?

What would be the algorithm to calculate the mean of the above numbers?

推荐答案

试试这个:

$total = 0;
$count = 0;
foreach($ratings as $number=>$frequency) {
  $total += $number * $frequency;
  $count += $frequency;
}
return $total / $count;

这篇关于如何计算加权平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆