0

I'm trying to calculate the variance of a vector of long doubles. I've tried implementing other code I've seen, but it doesn't return the correct value.

long double variance = 0;
for (int x = 0; x < (v.size() - 1); x++) {
    variance += (v.at(x) - mean) * (v.at(x) - mean);
}
variance /= v.size();

For example, if my vector is {1,2,3,4,5}, the above code gives me 2.25. To my understanding the correct answer is 2.

Any help is appreciated, I'm not sure what I'm missing.

Owl
  • 13
  • 1
  • 4
  • Try not to use explicit for loops, try to use STL algorithm like transform. Exact solution to your problem at https://stackoverflow.com/a/12405793/171755 – jbp Mar 15 '18 at 00:59

1 Answers1

3

x < (v.size() - 1)? This skips the last element. Use <= or omit the - 1.

The index of the element is v.size() - 1, and since x must be less than that, the loop breaks before the last element is processed.

eesiraed
  • 4,626
  • 4
  • 16
  • 34