Randomtheories
Randomtheories

Reputation: 1290

Var(x) and cov(x, x) don't give the same result in numpy

A property of the covariance is, that cov(x, x) = var(x)

However, in numpy I don't get the same result.

from numpy import var, cov

x = range(10)
y = var(x)
z = cov(x, x)[0][1]
print y, z

Am I doing something wrong here? How can I obtain the correct result?

Upvotes: 20

Views: 5476

Answers (2)

kennytm
kennytm

Reputation: 523264

The default ddof of cov (None) and var (0) are different. Try specifying the ddof (or bias):

>>> cov(x, x, ddof=0)
array([[ 8.25,  8.25],
       [ 8.25,  8.25]])
>>> var(x)
8.25

Upvotes: 12

George
George

Reputation: 5681

You must use z=cov(x,bias=1) in order to normalize by N ,because var is also norm by N (according to this

Upvotes: 24

Related Questions