00001 //#include <vector> 00002 //#include <iostream> 00003 //#include <math.h> 00004 #include <utility> 00005 #include <cmath> 00006 00007 using namespace std; 00008 00012 class stddev { 00013 private: 00014 double var; // variance 00015 double avg; 00016 int j; 00017 double SS; // sample variance 00018 00019 public: 00020 stddev() : j(0), var(0), avg(0), SS(0) {} 00021 void operator()(double x) { 00022 ++j; 00023 if (j==1) { avg = x; var = 0; SS=0; } 00024 else { double avgnew = avg + (x-avg)/(j); 00025 SS = (1-static_cast<double>(1)/(j-1))*SS + j*(avgnew-avg)*(avgnew-avg); 00026 var = (j-1)*(var/j + (avgnew-avg)*(avgnew-avg)); 00027 avg = avgnew; 00028 } 00029 //cerr << "n: " << j << " avg =" << avg 00030 // << " sqrt(SS)= " << sqrt(SS) << endl; 00031 } 00032 double getMean() const { return avg; } 00033 double getStd() const { return sqrt(var); } 00034 double getSampleStd() const { return sqrt(SS); } 00035 // postgres retuns the sample standard deviation 00036 pair<double, double> result() const { return make_pair(avg, sqrt(SS)); } 00037 }; 00038
1.5.6