简体   繁体   中英

How to calculate a weighted mean?

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
);

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?

Try this:

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

Wouldn't this work?

$total = 0;
$sum = 0;
foreach ($ratings as $k => $v) {
  $total += $k * $v;
  $sum += $v;
}
echo $total / $sum;

EDIT: Well, I look silly, since someone beat me to it. Oh well.

Doubt I can beat the accepted answer, but I find that built in looping functions run faster than scripted loops. Not sure how well the calls to $multiply are going to be optimized. If this is really slow then I expect someone will point it out in a comment.

function multiply( $k , $v ) { return $k * $v; }
return array_sum( array_map( 'multiply' , array_keys($ratings) , $ratings ) ) / array_sum( $ratings );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM