Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-10-25 04:54:55

0001 #ifndef CommonTools_Statistics_median_h
0002 #define CommonTools_Statistics_median_h
0003 
0004 #include <vector>
0005 #include <algorithm>
0006 #include <cmath>
0007 //#include "CommonDet/DetUtilities/interface/DetExceptions.h"
0008 
0009 //using namespace std;
0010 
0011 /**
0012  *  Median in one dimension.
0013  *  T must be sortable, 'addable', and dividable by 2.
0014  */
0015 template <class T>
0016 T median(std::vector<T> values) {
0017   switch (values.size()) {
0018     case 0:
0019       //      throw LogicError ("Median of empty vector");
0020     case 1:
0021       return values[0];
0022     case 2:
0023       return (values[0] + values[1]) / 2.;
0024   };
0025   T ret;
0026   const int size = values.size();
0027   const int half = (int)ceil(size / 2.);
0028   partial_sort(values.begin(), values.begin() + half + 1, values.end());
0029   if (size & 1) {
0030     ret = values[half - 1];
0031   } else {
0032     ret = (values[half - 1] + values[half]) / 2.;
0033   };
0034   return ret;
0035 }
0036 #endif