|
degate 0.1.1
|
00001 /* -*-c++-*- 00002 00003 This file is part of the IC reverse engineering tool degate. 00004 00005 Copyright 2008, 2009, 2010 by Martin Schobert 00006 00007 Degate is free software: you can redistribute it and/or modify 00008 it under the terms of the GNU General Public License as published by 00009 the Free Software Foundation, either version 3 of the License, or 00010 any later version. 00011 00012 Degate is distributed in the hope that it will be useful, 00013 but WITHOUT ANY WARRANTY; without even the implied warranty of 00014 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 00015 GNU General Public License for more details. 00016 00017 You should have received a copy of the GNU General Public License 00018 along with degate. If not, see <http://www.gnu.org/licenses/>. 00019 00020 */ 00021 00022 #ifndef __STATISTICS_H__ 00023 #define __STATISTICS_H__ 00024 00025 #include <vector> 00026 #include <algorithm> 00027 00028 namespace degate { 00029 00030 /** 00031 * Calculate the median of a vector. 00032 * @exception DegateRuntimeException This exception is thrown if 00033 * vector's size is 0. 00034 */ 00035 template<typename T> 00036 inline T median(std::vector<T> & v) { 00037 00038 if(v.empty()) 00039 throw DegateRuntimeException("Error in median(): The vector is empty."); 00040 00041 std::sort(v.begin(), v.end()); 00042 00043 unsigned int center = v.size()/2; 00044 00045 if(v.size() % 2 == 0) { 00046 return (v[center - 1] + v[center + 1]) / 2; 00047 } 00048 else 00049 return v[center]; 00050 } 00051 00052 00053 /** 00054 * Calculate the average of a vector. 00055 * @exception DegateRuntimeException This exception is thrown if 00056 * vector's size is 0. 00057 */ 00058 template<typename T> 00059 inline T average(std::vector<T> const& v) { 00060 00061 if(v.empty()) 00062 throw DegateRuntimeException("Error in average(): The vector is empty."); 00063 00064 double _sum = 0; 00065 00066 for(typename std::vector<T>::const_iterator iter = v.begin(); 00067 iter != v.end(); ++iter) 00068 _sum += *iter; 00069 00070 return _sum / (double)v.size(); 00071 } 00072 00073 00074 /** 00075 * Calculate the standard deviation of a vector. 00076 * @exception DegateRuntimeException This exception is thrown if 00077 * vector's size is 0. 00078 */ 00079 template<typename T> 00080 inline T standard_deviation(std::vector<T> const& v) { 00081 00082 if(v.empty()) 00083 throw DegateRuntimeException("Error in standard_deviation(): The vector is empty."); 00084 00085 T avg = average<T>(v); 00086 double sum = 0; 00087 for(typename std::vector<T>::const_iterator iter = v.begin(); iter != v.end(); ++iter) 00088 sum += pow(avg - *iter, 2); 00089 00090 return sqrt(sum/(double)v.size()); 00091 } 00092 00093 00094 00095 } 00096 00097 00098 00099 #endif
1.7.4