Home > Back-end >  Why the weighted average get unintended result?
Why the weighted average get unintended result?

Time:12-07

we know the weighted average formula is:

so, when I use numpy:

a = np.array([1,2,3,4])

wts = np.array([1,2,3,4])
print(np.average(a, weights=wts))

it should be:

np.sum([1*1, 2*2, 3*3, 4*4]) / 4   # 7.5 

but why get 3.0?

CodePudding user response:

According to the doc of average, the average is

avg = sum(a * weights) / sum(weights)

If you want to divide by the number of weights instead of the summation, you can simply do

a = np.array([1,2,3,4])
wts = np.array([1,2,3,4])

np.dot(a,wts) / wts.shape[0]
  • Related