Skip to content

Instantly share code, notes, and snippets.

@albertyumol
Created October 23, 2019 06:53
Show Gist options
  • Save albertyumol/a135760cb2f1f4507045e49c4b67470a to your computer and use it in GitHub Desktop.
Save albertyumol/a135760cb2f1f4507045e49c4b67470a to your computer and use it in GitHub Desktop.
Calculate the covariance in Python.
#Provided that x and y have the same length.
import numpy as np
def covariance(x, y):
N = len(x)
x_bar = np.mean(x)
y_bar = np.mean(y)
deviation_mean_x = [x_i - x_bar for x_i in x]
deviation_mean_y = [y_i - y_bar for y_i in y]
return np.dot(deviation_mean_x, deviation_mean_y) / N
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment