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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With