How to calculate a weighted average?

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

I have an associative array of ratings (let) and the number of times the rating has been assigned.

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

This is the equivalent: [1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5] , but given the number I am working with, it would be perfectly it is inefficient to convert from the first form to the second.

What will be the algorithm for calculating the average of the above numbers?

+4
source share
3 answers

Try the following:

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

Does this work?

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

EDIT: Well, I look stupid since someone beat me up. Oh good.

+10
source

I doubt that I can beat the accepted answer, but found that the built-in functions of the loop work faster than scripts. Not sure how well $ multiply calls will be optimized. If it is very slow, I expect someone to 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 ); 
+3
source

All Articles