Reputation: 707
I am trying to compute this equation in python but I'm having problem understanding the loop and I am kinda confused at the summation of the summation.
This is how far i got and I have trouble implementing the summation of the summation. Any idea?
import numpy as np
stdev =np.zeros(N)
m_sum=np.zeros([lam,N])
for i in xrange(N):
for k in xrange(lam):
m_sum[k,i]+=(1/(lam))*m[k,i]
stdev[i]=1/(lam-1)*(m[k,i]-m_sum[k,i])**2
Upvotes: 0
Views: 954
Reputation: 18617
It's confusing because the same index variable k
is being used for both inner and outer loop, so it's ambiguous. However, since this is the standard formula for standard deviation, we know from context what the intention is:
import math
import numpy as np
stdev = np.zeros(N)
means = np.zeros(N)
for i in xrange(N):
m = 0
for k in xrange(lam):
m += m[k,i]
means[i] = m/lam
v = 0
for k in xrange(lam):
v += (m[k,i] - means[i])**2
stdev[i] = math.sqrt(v)/(lam-1)
Note that numpy
also has functions to directly calculate standard deviations of columns of your matrix m
, but if you're just doing this as an exercise of directly translating a math equation into code, then this is how you would do it.
Upvotes: 2