All formulas

Statistics

Sample covariance

stats.sample-covarianceAlso called sample covariance, covariance, cov, unbiased covariance

sxy=1n−1∑i=1n(xi−xˉ)(yi−yˉ)s_{xy} = \frac{1}{n-1}\sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})

wherexˉ=1n∑j=1nxj\bar{x} = \frac{1}{n}\sum_{j=1}^{n} x_j

whereyˉ=1n∑j=1nyj\bar{y} = \frac{1}{n}\sum_{j=1}^{n} y_j

Unbiased estimate of the covariance of two paired samples, dividing by n − 1.

Notation

xx

first variable

x ∈ ℝn

yy

second variable

y ∈ ℝn

nn

number of observations

Size, at least 2

sxys_{xy}

Result: the sample covariance

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    x=[1,2,3,4],y=[2,4,5,9]x = [1, 2, 3, 4], y = [2, 4, 5, 9]

    Result

    sxy=113\displaystyle s_{xy} = \frac{11}{3}

    ≈ 3.66666666667

  2. Given

    x=[1,2,3],y=[3,2,1]x = [1, 2, 3], y = [3, 2, 1]

    Result

    sxy=−1\displaystyle s_{xy} = -1
  3. Given

    x=[0.5,1.5],y=[2,−2]x = [0.5, 1.5], y = [2, -2]

    Result

    sxy=−2\displaystyle s_{xy} = -2

Common mistakes

  • Divides by n instead of n − 1

    This is the population covariance (np.cov with bias=True); the result is (n − 1)/n times the sample value.

    Fix: Divide by n − 1.

Source

  • Casella and Berger 2002

    Casella, George; Berger, Roger L. Statistical Inference. 2nd ed. Duxbury, 2002.