Reference · Statistics
stats.covariance
stats.covariance(list, list) -> floatWhat it does
The sample covariance of two lists of numbers of the same length: how much they
vary together, as Python's statistics.covariance. Positive when the pairs rise
together, negative when one falls as the other rises, near zero when they are
unrelated. The sum of the products of the distances from each mean is divided by
one less than the count. Its scale is the data's, so for a scale-free measure use
stats.correlation.
Examples
let x = [1, 2, 3, 4, 5, 6, 7, 8, 9]let y = [1, 2, 3, 1, 2, 3, 1, 2, 3]let z = [9, 8, 7, 6, 5, 4, 3, 2, 1]print(stats.covariance(x, y), stats.covariance(x, z))0.75 -7.5Edge cases
- The order of the two lists does not matter.
- A list with itself gives its sample variance.
- A constant list gives
0.0. - Two points are enough.
- Ints and floats can mix; the answer is always a float.
print(stats.covariance([1, 2, 3], [3, 2, 1]), stats.covariance([3, 2, 1], [1, 2, 3]))print(stats.covariance([1, 2, 3], [1, 2, 3]) == stats.variance([1, 2, 3]))print(stats.covariance([1, 2], [3, 3]), stats.covariance([1, 2], [2, 4.0]))-1.0 -1.0true0.0 1.0Errors
Lists of different lengths, fewer than two points, or an item that is not a number are each a runtime error, not an error value.
print(stats.covariance([1, 2, 3], [1, 2]))line 1: `stats.covariance` needs lists of the same length (3 and 2)print(stats.covariance([1], [2]))line 1: `stats.covariance` requires at least two data pointsChaining
In a pipeline the first list comes first and the second is the argument:
let ads = [10, 20, 30, 40]let sales = [110, 190, 310, 390]print(ads | stats.covariance(sales))print((ads | stats.covariance(sales)) / stats.variance(ads))1600.09.600000000000001See also
stats.correlation, stats.variance, stats.linear_regression
Thread 0 posts
On stats.covariance(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo