Advertisement
Guest User

upper_bound

a guest
Sep 19th, 2011
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. function upper_bound ($a)
  2. {
  3.  
  4.   //Use this many standard deviations as upper bound
  5.   $max_std_devs = 3;
  6.   $max_val = 0;
  7.   $removed_items = 1;
  8.  
  9.   while ($removed_items && count($a) > 0) { // Continue as long as 'outliers' are found
  10.     $removed_items = 0;
  11.     $the_variance = 0.0;
  12.     $the_mean = 0.0;
  13.     $the_array_sum = array_sum($a); //sum the elements
  14.     $number_elements = count($a); //count the number of elements
  15.  
  16.     //calculate the mean
  17.     $the_mean = $the_array_sum / $number_elements;
  18.  
  19.     //calculate the variance
  20.     for ($i = 0; $i < $number_elements; $i++)
  21.     {
  22.         //sum the array
  23.         $the_variance = $the_variance + ($a[$i] - $the_mean) * ($a[$i] - $the_mean);
  24.     }
  25.  
  26.     $the_variance = $the_variance / $number_elements;
  27.  
  28.     $max_val = $the_mean + ($max_std_devs * sqrt($the_variance));
  29.  
  30.     foreach($a as $key => $value) {
  31.         if ($value > $max_val) {
  32.           unset($a[$key]);
  33.           $removed_items = 1;
  34.         }
  35.     }
  36.     $array = array_values($a);
  37.   }
  38.  
  39.   return ceil($max_val);
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement