Home > Commands -> Function Commands -> covariance


EXAMPLES ON MY SAGE PAGE: Scatterplots


Goal: Find the covariance between a list of x and list of y data values


def covariance(x_data,y_data) :
   n=len(x_data); c=0.
   if n==len(y_data) :
      xy_data=[x_data[j]*y_data[j] for j in range(n)]
      c=mean(xy_data)-mean(x_data)*mean(y_data)
   return float(c)


  • Example 1
    x_d = [18,23,25,35,65,54]                  # ages of individuals
    y_d = [202,186,187,180,156,169]      # maximum heart rate of each one
    cov=covariance(x_d,y_d)
    print cov
    Result:
    -240.833333333

Your responsibility: x_data and y_data to be lists of numbers; if 0 is returned, your lists are not the same length.

Sage commands used: len, mean, Operations on Lists


Related SageMath Pages: fit_line,scatter_plot


Keywords: covariance, correlation, scatterplot, regression