# brendano/running_stat

Switch branches/tags
Nothing to show
Fetching contributors…
Cannot retrieve contributors at this time
176 lines (146 sloc) 4.67 KB
 // A C++ implementation of running variance/standard deviation (Welford 1962) // This follows http://www.johndcook.com/standard_deviation.html // By brendan o'connor, anyall.org // See main() on bottom for how to use // % g++ running_stat.cc ## after editing in the main() // % ./a.out // added 0 now mean=0.00 var=0.00 std=0.00 // added 1 now mean=0.50 var=0.25 std=0.50 // added 2 now mean=1.00 var=0.67 std=0.82 // added 3 now mean=1.50 var=1.25 std=1.12 // added 4 now mean=2.00 var=2.00 std=1.41 // added 5 now mean=2.50 var=2.92 std=1.71 // added 6 now mean=3.00 var=4.00 std=2.00 // added 7 now mean=3.50 var=5.25 std=2.29 // added 8 now mean=4.00 var=6.67 std=2.58 // added 9 now mean=4.50 var=8.25 std=2.87 #include #include #include using namespace std; class RunningStat { public: double ss; // (running) sum of square deviations from mean double m; // (running) mean // double last_m; double n; // unsigned int n; // number of items seen double totalW; // weight of items seen bool is_started; RunningStat() : ss(0), m(0), n(0), totalW(0), is_started(false) {} void add(double x) { add(x,1); } void add(double x, double w) { n++; if (!is_started) { m = x; ss = 0; totalW = w; is_started = true; } else { float tmpW = totalW + w; ss += totalW*w * (x-m)*(x-m) / tmpW; m += (x-m)*w / tmpW; totalW = tmpW; } } double var() const { return ss / totalW; } double sd() const { return sqrt(var()); } double mean() const { return m; // if (w) return m / (w/n); // return m; } }; ostream& operator<<(ostream& output, const RunningStat& rs) { // output << "mean=" << rs.mean() << " sd=" << rs.sd() << " n="<