Skip to content

Instantly share code, notes, and snippets.

Created November 24, 2015 06:10
weighted standard deviation
#include "standarddeviation.h"
stddev::StandardDeviation::StandardDeviation(const std::vector<stddev::sampleGroup> &population):
m_Avg(0),
m_Weight(0),
m_StdDev(0),
m_StdError(0) {
// If there are no samples just skip everything and keep all zeros
if (!population.empty()) {
// Weighted Calculation of the Standard Deviation using the incremental method
// from https://en.wikipedia.org/wiki/Standard_deviation
long double q = 0;
for (auto n : population) {
if (!n.weight == 0) {
//Math magic
m_Weight += n.weight;
double delta = n.weight * (n.value - m_Avg);
m_Avg += delta / m_Weight;
q += delta * (n.value - m_Avg);
}
}
//m_StdDev = pow(q / m_Weight, 0.5); // Population
m_StdDev = pow(q / (m_Weight - 1), 0.5); // Sample
// Standard Error is the (sample) Standard Deviation divided by the square root of the weight
m_StdError = m_StdDev / pow(m_Weight, 0.5);
}
}
#pragma once
#include <cmath> // pow raise to the power
#include <vector>
namespace stddev {
struct sampleGroup {
double value; // what was value
double weight; // how many times is the value to be counted
};
class StandardDeviation {
public:
/** Default constructor */
explicit StandardDeviation(const std::vector<stddev::sampleGroup> &dataIn);
const double GetAvg() {
return m_Avg;
}
const double GetWeight() {
return m_Weight;
}
const double GetStdDev() {
return m_StdDev;
}
const double GetStdError() {
return m_StdError;
}
protected:
private:
double m_Avg;
double m_Weight;
double m_StdDev;
double m_StdError;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment