variance

I'm trying to write c++ code to calculate the variance of an array, but I'm not having much luck, not being used to computer languages. I haven't included all the code below, but could someone give me a hint at where my loop is going wrong... The method goes through an array and updates the variance at each step. This is what it's supposed to do: variance(samples):
M := 0
S := 0
for k from 1 to N:
x := samples[k]
oldM := M
M := M + (x-M)/k
S := S + (x-M)*(x-oldM)
return S/(N-1)


1
2
3
4
5
6
7
8
9
10
11
12
  int n = xx.size();
int k;
double mu = xx[0];
double ss = 0;
for(k = 1; k < n; k++) {

double muNew = mu[k-1] + (xx[k] - mu[k-1])/k;
ss[k] += (x[k] - mu[k-1]) * (xx[k] - muNew)
mu[k] = muNew;

}
return(ss[k]/(n - 1);
Last edited on
The variable 'mu' is of type double, not an array. So there is no element to access at 'k - 1'. If I had to guess at what you are trying to do, I would say that you want 'mu' to be a pointer.
M := 0
S := 0
for k from 1 to N:
x := samples[k]
oldM := M
M := M + (x-M)/k
S := S + (x-M)*(x-oldM)
return S/(N-1)

Who gave you that?

for k from 1 to N:
x := samples[k]
Do you mean that you want to start from the first element?
If the answer is yes then your loop has to go from k = 0 while k < n because index 0 is the first element.

1
2
3
4
5
6
double mu = xx[0]; 
// ...

// mu is NOT an array, it is a double so you can't access mu[k-1]
double muNew = mu[k-1] + (xx[k] - mu[k-1])/k;
mu[k] = muNew;

I think you just want mu and not mu[k-1] everywhere.
you also probably want mu = muNew instead of mu[k] = muNew

same thing with ss and ss[k]:
ss[k] += (x[k] - mu[k-1]) * (xx[k] - muNew);


Last edited on
Thanks for your help.

I got the outline algorithm from the internet. It's Welford's variance algorithm.

Thanks again, Rob.
You're welcome!

Is your problem solved now?
Last edited on
Yes, thanks Gamer. Can I mark it as solved?

It compiles and runs now.
Topic archived. No new replies allowed.