Calculating Standard Deviation & Variance in C++
Here's another approach using std::accumulate
but without using pow
. In addition, we can use an anonymous function to define how to calculate the variance after we calculate the mean. Note that this computes the unbiased sample variance.
#include <vector>
#include <algorithm>
#include <numeric>
template<typename T>
T variance(const std::vector<T> &vec) {
const size_t sz = vec.size();
if (sz == 1) {
return 0.0;
}
// Calculate the mean
const T mean = std::accumulate(vec.begin(), vec.end(), 0.0) / sz;
// Now calculate the variance
auto variance_func = [&mean, &sz](T accumulator, const T& val) {
return accumulator + ((val - mean)*(val - mean) / (sz - 1));
};
return std::accumulate(vec.begin(), vec.end(), 0.0, variance_func);
}
A sample of how to use this function:
#include <iostream>
int main() {
const std::vector<double> vec = {1.0, 5.0, 6.0, 3.0, 4.5};
std::cout << variance(vec) << std::endl;
}
As the other answer by horseshoe correctly suggests, you will have to use a loop to calculate variance otherwise the statement
var = ((Array[n] - mean) * (Array[n] - mean)) / numPoints;
will just consider a single element from the array.
Just improved horseshoe's suggested code:
var = 0;
for( n = 0; n < numPoints; n++ )
{
var += (Array[n] - mean) * (Array[n] - mean);
}
var /= numPoints;
sd = sqrt(var);
Your sum works fine even without using loop because you are using accumulate function which already has a loop inside it, but which is not evident in the code, take a look at the equivalent behavior of accumulate for a clear understanding of what it is doing.
Note: X ?= Y
is short for X = X ? Y
where ?
can be any operator.
Also you can use pow(Array[n] - mean, 2)
to take the square instead of multiplying it by itself making it more tidy.
Your variance calculation is outside the loop and thus it is only based on the n== 100
value. You need an additional loop.
You need:
var = 0;
n=0;
while (n<numPoints){
var = var + ((Array[n] - mean) * (Array[n] - mean));
n++;
}
var /= numPoints;
sd = sqrt(var);
Two simple methods to calculate Standard Deviation & Variance in C++.
#include <math.h>
#include <vector>
double StandardDeviation(std::vector<double>);
double Variance(std::vector<double>);
int main()
{
std::vector<double> samples;
samples.push_back(2.0);
samples.push_back(3.0);
samples.push_back(4.0);
samples.push_back(5.0);
samples.push_back(6.0);
samples.push_back(7.0);
double std = StandardDeviation(samples);
return 0;
}
double StandardDeviation(std::vector<double> samples)
{
return sqrt(Variance(samples));
}
double Variance(std::vector<double> samples)
{
int size = samples.size();
double variance = 0;
double t = samples[0];
for (int i = 1; i < size; i++)
{
t += samples[i];
double diff = ((i + 1) * samples[i]) - t;
variance += (diff * diff) / ((i + 1.0) *i);
}
return variance / (size - 1);
}