Reputation: 546075
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?
Upvotes: 4
Views: 6332
Reputation: 7712
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 );
Upvotes: 3
Reputation: 1190
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.
Upvotes: 10
Reputation: 16249
Try this:
$total = 0;
$count = 0;
foreach($ratings as $number=>$frequency) {
$total += $number * $frequency;
$count += $frequency;
}
return $total / $count;
Upvotes: 17