code_junkie

How to calculate a weighted mean

Nov 13th, 2011
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. $ratings = array(
  2. 1 => 1,
  3. 2 => 3,
  4. 3 => 6,
  5. 4 => 3,
  6. 5 => 3
  7. );
  8.  
  9. $total = 0;
  10. $count = 0;
  11. foreach($ratings as $number=>$frequency) {
  12. $total += $number * $frequency;
  13. $count += $frequency;
  14. }
  15. return $total / $count;
  16.  
  17. $total = 0;
  18. $sum = 0;
  19. foreach ($ratings as $k => $v) {
  20. $total += $k * $v;
  21. $sum += $v;
  22. }
  23. echo $total / $sum;
  24.  
  25. function multiply( $k , $v ) { return $k * $v; }
  26. return array_sum( array_map( 'multiply' , array_keys($ratings) , $ratings ) ) / array_sum( $ratings );
Add Comment
Please, Sign In to add comment