BY: Statistics Fundamentals Team
Reviewed By: Minsa A (Senior Statistics Editor)
Updated:

Covariance Calculator

Enter two lists of numbers and get the covariance, both means, the correlation and the full working. Switch between sample covariance (divide by n − 1) and population covariance (divide by n). Other tabs handle a joint probability table, a covariance matrix for three or more variables, and conversion between covariance and correlation. Everything runs in your browser.

  Back to all statistics calculators

Covariance calculator

Formula Cov(X, Y) = Σ(xi − x̄)(yi − ȳ) / (n − 1) Use when data is a sample
Separate values with commas, spaces or new lines, and use a period for decimals. X and Y need the same number of values, and the nth X pairs with the nth Y.
Formula Cov(X, Y) = E[XY] − E[X]E[Y] Use for discrete random variables
Each line is a pair of values and its probability P(X = x, Y = y). The probabilities must add up to 1.
Matrix entry C[i][j] = Cov(Xi, Xj) Diagonal variances
Separate columns with commas, tabs or spaces, so you can paste straight from a spreadsheet. An optional first row of names (one word each) labels the variables. Two to twelve variables.
Formula Cov(X, Y) = r × sX × sY Use when you have summary statistics only
The standard deviations must use the same divisor as the covariance. Sample standard deviations give a sample covariance, and population standard deviations give a population covariance.

Run a calculation in any other tab first. The working for the most recent one appears here.

No data yet. Enter values in one of the other tabs.

What is covariance?

Covariance is a number that shows whether two variables tend to move in the same direction. It is positive when X and Y are usually above their own averages at the same time, negative when one tends to be above average while the other is below, and close to zero when there is no linear pattern.

Formally, it is the average product of each variable's deviation from its mean. Variance is the special case where both variables are the same, so Cov(X, X) = Var(X). Covariance carries the units of X multiplied by the units of Y, which is why its size is hard to read on its own. Pearson correlation removes the units by dividing by the two standard deviations.

This page is about the statistical quantity. It has no connection to the coefficient of variation, which is a standard deviation divided by a mean and is sometimes abbreviated CV or COV.

Covariance formula

There are two versions, and the only difference is the divisor. Use n − 1 when your data is a sample from a larger group and n when the data is the whole group.

Sample covariance

Cov(X, Y) = Σ(xi − x̄)(yi − ȳ) / (n − 1)

Written sXY in many textbooks. Needs at least two pairs.

Population covariance

Cov(X, Y) = Σ(xi − μX)(yi − μY) / N

Written σXY. N is the number of members in the whole population.

Expected-value form

Cov(X, Y) = E[(X − E[X])(Y − E[Y])] = E[XY] − E[X]E[Y]

Used for random variables and probability tables. The second line follows by expanding the product.

Computational shortcut

Cov(X, Y) = (Σxiyi − n·x̄·ȳ) / (n − 1)

Gives the same sample result. It loses precision when the values are large and close together, so the deviation form is safer in code.

Here n is the number of (x, y) pairs, x̄ and ȳ are the two sample means, and the sum runs over every pair. For the same numbers, the sample value is always n / (n − 1) times the population value. In the worked example below, 34 × 5 / 4 = 42.5.

How to calculate covariance by hand

Take five students, with x as hours studied and y as exam score. The values are chosen so that both means come out as whole numbers.

Deviations and products for the five students (x̄ = 6, ȳ = 75)
Studentxyx − 6y − 75(x − 6)(y − 75)
1260−4−1560
2465−2−1020
3675000
48802510
5109542080
Total3037500170
1

Find the two means

x̄ = (2 + 4 + 6 + 8 + 10) / 5 = 6 and ȳ = (60 + 65 + 75 + 80 + 95) / 5 = 75.

2

Subtract the mean from every value

These are the deviations in columns 4 and 5. Each column adds to zero, which is a quick check on the arithmetic.

3

Multiply each pair of deviations

The products are 60, 20, 0, 10 and 80.

4

Add the products

Σ(x − x̄)(y − ȳ) = 60 + 20 + 0 + 10 + 80 = 170.

5

Divide by n − 1 or n

Sample covariance = 170 / (5 − 1) = 42.5. Population covariance = 170 / 5 = 34.

6

Read the sign and check with correlation

The positive sign means students who studied more hours tended to score higher. The sample standard deviations are sX = 3.1623 and sY = 13.6931, so r = 42.5 / (3.1623 × 13.6931) = 0.9815.

Sample covariance 42.5, population covariance 34, correlation 0.9815. The shortcut formula agrees: Σxy = 2,420 and n·x̄·ȳ = 5 × 6 × 75 = 2,250, so (2,420 − 2,250) / 4 = 42.5.

Sample vs population covariance

Pick population covariance when the data contains every member of the group you are describing, for example all twelve monthly figures of a year you are reporting on. Pick sample covariance when the data is a subset used to estimate something about a larger group, which is the usual case in surveys, experiments and coursework.

A sample mean sits closer to the sample's own values than the true population mean would, so dividing the squared-deviation sums by n understates the spread. Dividing by n − 1 corrects for that and is known as Bessel's correction. The same reasoning is behind the population vs sample distinction for variance and standard deviation.

Sample and population covariance side by side
ItemSample covariancePopulation covariance
Divisorn − 1n (or N)
Common symbolsXY or Cov(X, Y)σXY
Minimum number of pairs21
Excel functionCOVARIANCE.SCOVARIANCE.P
Result for the five students42.534

The choice matters most for small data sets. With five pairs the sample value is 25% larger than the population value, and with 100 pairs the gap shrinks to about 1%.

How to interpret covariance

Positive, negative and zero covariance

What the sign of covariance says
SignMeaningPattern in a scatter plot
PositiveY tends to be higher when X is higherPoints run from lower left to upper right
NegativeY tends to be lower when X is higherPoints run from upper left to lower right
Zero or near zeroNo linear trend between X and YA shapeless cloud, or a curve with no overall tilt

A scatter plot shows the sign immediately, and the calculator above draws one with the two means marked. You can build your own with the scatter plot maker.

Why the size of covariance is hard to read

Rescaling a variable rescales the covariance by the same factor, even though the relationship is unchanged. Take six people with heights of 160, 165, 170, 175, 180 and 185 cm and weights of 58, 60, 68, 70, 78 and 77 kg.

Same six people, three unit choices
Units (height, weight)Sample covarianceCorrelation r
Centimetres, kilograms75.50.9682
Metres, kilograms0.7550.9682
Inches, pounds65.530.9682

The relationship is identical in all three rows, yet the covariance ranges from 0.755 to 75.5. Correlation stays at 0.9682 because it has no units. Covariance does have a ceiling: its absolute value can never exceed sX × sY. That ceiling changes with the data, so there is no universal cutoff such as 1.

Zero covariance does not prove independence

Covariance only picks up linear co-movement. Let X be −1, 0 or 1 with probability 1/3 each, and let Y = X2. Then E[X] = 0 and E[XY] = E[X3] = 0, so Cov(X, Y) = 0, yet Y is completely determined by X. The reverse statement does hold: if X and Y are independent and have finite variances, their covariance is zero.

Outliers can dominate the result

One extreme pair adds one very large product to the sum. In the five-student example, change the last score from 95 to 200. The sample covariance jumps from 42.5 to 147.5, while the correlation falls from 0.9815 to 0.7950 because the standard deviation of y grows even faster. Look at the plot before reporting either number, and see the guide to outliers for ways to spot them.

Covariance vs correlation

Correlation is covariance rescaled to the range −1 to 1: r = Cov(X, Y) / (sX × sY). Dividing by both standard deviations removes the units, so r is the same in centimetres or inches. Another way to see it is that r equals the covariance of the two z-scores.

Covariance compared with Pearson correlation
PropertyCovariancePearson correlation
SymbolCov(X, Y), sXY, σXYr, ρ
RangeNo fixed range; limited by sX × sY−1 to 1
UnitsUnits of X times units of YNone
Changes when a variable is rescaledYesNo
Shows directionYesYes
Shows strengthNoYes, for linear relationships
Typical useCovariance matrices, portfolio variance, PCA, regression slopesReporting and comparing relationships

The two are linked to regression as well. The least-squares slope of Y on X is Cov(X, Y) / Var(X), which is covered in the slope and intercept guide. To move between covariance and correlation, use the fourth tab of the calculator or the correlation calculator. If your correlation is rank-based, see Pearson vs Spearman, and remember that neither number shows causation.

Covariance of two random variables

For two discrete random variables with a joint probability table, covariance uses expected values: Cov(X, Y) = E[XY] − E[X]E[Y]. Each expected value is a probability-weighted sum over the table.

Joint distribution P(X = x, Y = y)
X \ YY = 1Y = 2P(X = x)
X = 10.200.050.25
X = 20.150.200.35
X = 30.050.350.40
P(Y = y)0.400.601.00
1

E[X] and E[Y]

E[X] = 1(0.25) + 2(0.35) + 3(0.40) = 2.15. E[Y] = 1(0.40) + 2(0.60) = 1.6.

2

E[XY]

Multiply x, y and the probability in each cell, then add: 0.20 + 0.10 + 0.30 + 0.80 + 0.15 + 2.10 = 3.65.

3

Covariance

Cov(X, Y) = 3.65 − 2.15 × 1.6 = 3.65 − 3.44 = 0.21.

The variances are Var(X) = 0.6275 and Var(Y) = 0.24, so the correlation is ρ = 0.21 / √(0.6275 × 0.24) = 0.5411. For independent variables the joint probability factors into the product of the two marginals, which forces E[XY] = E[X]E[Y] and a covariance of zero. See the expected value guide for the sums used here, or the expected value calculator for a single variable.

Covariance matrix

With k variables, the covariance matrix is a k × k table whose entry in row i and column j is Cov(Xi, Xj). The diagonal holds the variances, and the matrix is symmetric because Cov(Xi, Xj) = Cov(Xj, Xi). It is also positive semi-definite, which is what allows methods such as principal component analysis to take its eigenvectors.

For an example, add a third variable to the five students: the number of practice tests taken (3, 5, 4, 7 and 8). The sample covariance matrix is:

Sample covariance matrix for hours, score and practice tests
HoursScoreTests
Hours1042.56
Score42.5187.525
Tests6254.3

Dividing each entry by the product of the two standard deviations gives the correlation matrix, which has ones on the diagonal: 0.9815 for hours and score, 0.9150 for hours and tests, and 0.8805 for score and tests. The third tab of the calculator produces both matrices from pasted data. The same matrix feeds into multiple linear regression, where the covariances between predictors drive the coefficient estimates.

Covariance in finance

Portfolio risk depends on how asset returns move together. For two assets with weights w1 and w2, the variance of the portfolio return is

σp2 = w12σ12 + w22σ22 + 2·w1·w2·Cov(R1, R2)

Take a 60/40 split between two assets whose returns have standard deviations of 20% and 10%. The table shows how the portfolio's standard deviation falls as the covariance falls.

Portfolio standard deviation for a 60/40 split (20% and 10% volatility)
CorrelationCov(R1, R2)Portfolio std dev
1.00.020016.00%
0.30.006013.74%
0.00.000012.65%
−0.5−0.010010.58%

At a correlation of 1 the portfolio standard deviation equals the weighted average, 0.6 × 20% + 0.4 × 10% = 16%. Any lower covariance pulls it below that, which is the arithmetic behind diversification. In practice the covariances are estimated from historical return series with the sample formula, and they shift over time. These numbers are invented for illustration and are not investment advice. The finance articles on portfolio diversification statistics and statistics in risk management cover the wider context.

Covariance in Excel, Google Sheets, Python, R and TI-84

Software defaults differ, which is the usual reason a hand calculation and a spreadsheet disagree. Microsoft's COVARIANCE.S page gives =COVARIANCE.S({2,4,8},{5,11,12}) = 9.6667 as a test case, and you can paste those two lists into the calculator to confirm it.

Covariance functions by tool
ToolSample covariancePopulation covarianceNote
Excel=COVARIANCE.S(A2:A6, B2:B6)=COVARIANCE.P(A2:A6, B2:B6)The older COVAR is kept for compatibility and returns the population version.
Google Sheets=COVARIANCE.S(data_y, data_x)Multiply the sample result by (n − 1) / nGoogle's help page for COVAR does not say which version it returns, so test it against a hand example first.
Python (NumPy)np.cov(x, y)[0, 1]np.cov(x, y, ddof=0)[0, 1]Returns the full 2 × 2 matrix. Each row is a variable unless you pass rowvar=False.
Python (pandas)df["x"].cov(df["y"])df["x"].cov(df["y"], ddof=0)df.cov() returns the whole matrix with the sample divisor.
Rcov(x, y)cov(x, y) * (n - 1) / nR divides by n − 1.
TI-84r × Sx × SyMultiply the sample result by (n − 1) / nNo direct covariance command. Get Sx and Sy from 2-Var Stats and r from LinReg(ax+b) with DiagnosticOn.

The same five students in code. In every case the sample result is 42.5 and the population result is 34.

# Python import numpy as np x = [2, 4, 6, 8, 10] y = [60, 65, 75, 80, 95] np.cov(x, y) # [[ 10. , 42.5], [ 42.5, 187.5]] sample np.cov(x, y, ddof=0) # [[ 8. , 34. ], [ 34. , 150. ]] population # R x <- c(2, 4, 6, 8, 10); y <- c(60, 65, 75, 80, 95) cov(x, y) # 42.5 # Excel, with x in A2:A6 and y in B2:B6 =COVARIANCE.S(A2:A6, B2:B6) # 42.5 =COVARIANCE.P(A2:A6, B2:B6) # 34

For more on the Python side, see the statistics for Python article.

Properties of covariance

Rules for working with covariance
PropertyStatementWhat it is used for
SymmetryCov(X, Y) = Cov(Y, X)Order of the two variables does not matter
Relation to varianceCov(X, X) = Var(X)The diagonal of a covariance matrix
Scaling and shiftingCov(aX + b, cY + d) = ac · Cov(X, Y)Explains the unit effect: shifts change nothing, scale factors multiply
AdditivityCov(X + Z, Y) = Cov(X, Y) + Cov(Z, Y)Splitting a sum into parts
Variance of a sumVar(X + Y) = Var(X) + Var(Y) + 2 Cov(X, Y)Portfolio variance, error propagation
IndependenceIndependent implies Cov(X, Y) = 0, but not the reverseSee the Y = X2 example above
Upper bound|Cov(X, Y)| ≤ sX sYCauchy–Schwarz inequality; it is why |r| ≤ 1

In time series, the covariance of a series with a time-shifted copy of itself is called autocovariance, and the covariance between two different series at a given lag is called cross-covariance. Both use the same product-of-deviations idea as above.

Common mistakes

  • Sorting or filtering one list without the other breaks the pairing and changes the answer. Row i of X must stay with row i of Y.
  • Software defaults differ. Excel's COVAR and COVARIANCE.P divide by n, while np.cov, R's cov and COVARIANCE.S divide by n − 1, so results will not match until you align them.
  • Calling np.cov(data) on a table with variables in columns returns a matrix of the wrong shape, because NumPy treats each row as a variable. Pass rowvar=False.
  • A large covariance does not mean a strong relationship. Two variables measured in dollars and grams can produce a huge covariance from a weak association, so check r.
  • Covariance misses curved relationships. A U-shaped pattern can have a covariance near zero.
  • The conversion Cov = r × sX × sY needs standard deviations with the same divisor as the covariance you want.

Covariance connects descriptive statistics to correlation and regression. These pages cover the topics on either side.

Sources

Frequently asked questions

What is covariance?

Covariance measures whether two variables tend to move together. A positive value means they usually rise and fall together, a negative value means one tends to rise when the other falls, and a value near zero means there is no linear trend. Its size depends on the units of both variables, so it is usually read alongside the correlation coefficient.

What is the formula for covariance?

For a sample, Cov(X, Y) = Σ(xi − x̄)(yi − ȳ) / (n − 1). For a population, divide by N instead. The expected-value form is Cov(X, Y) = E[XY] − E[X]E[Y]. For x = 2, 4, 6, 8, 10 and y = 60, 65, 75, 80, 95 the sample covariance is 42.5.

Should I use sample or population covariance?

Use population covariance (divide by n) when your data includes every member of the group you are describing. Use sample covariance (divide by n − 1) when the data is a subset used to estimate a larger group, which covers most surveys, experiments and coursework. The sample value equals n / (n − 1) times the population value.

How do I calculate covariance in Excel?

Use =COVARIANCE.S(array1, array2) for a sample and =COVARIANCE.P(array1, array2) for a population. The older COVAR function returns the population version. For example, =COVARIANCE.S({2,4,8},{5,11,12}) returns 9.6667.

What does negative covariance mean?

Negative covariance means that when one variable is above its mean, the other tends to be below its own mean. A used car's age and its resale price are a typical example. The size of the number says nothing about strength unless you also check the correlation.

Does zero covariance mean the variables are independent?

No. Independent variables have zero covariance, but zero covariance does not imply independence. If X is −1, 0 or 1 with equal probability and Y = X2, the covariance is 0 even though Y is completely determined by X.

What is the difference between covariance and correlation?

Correlation is covariance divided by the product of the two standard deviations, r = Cov(X, Y) / (sX × sY). That makes it unit-free and limited to the range −1 to 1. Covariance keeps the units of X times the units of Y and has no fixed range, which makes it useful as an input to other calculations.

Why is covariance not limited to between −1 and 1?

Covariance is not standardized, so rescaling a variable rescales the covariance. The same height and weight data give 75.5 in centimetres and kilograms but 0.755 in metres and kilograms. The only bound is that the absolute covariance cannot exceed the product of the two standard deviations.

What is a covariance matrix?

A covariance matrix is a square table of every pairwise covariance among k variables. The diagonal holds the variances and the matrix is symmetric. It is used in principal component analysis, multivariate regression and portfolio risk. The Covariance matrix tab above builds one from pasted data.

How do I get covariance from correlation?

Multiply the correlation by the two standard deviations: Cov(X, Y) = r × sX × sY. With r = 0.8, sX = 5 and sY = 12 the covariance is 48. Use standard deviations that match the covariance you want, sample or population.

  Back to all statistics calculators