MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / covariance

Function covariance

maths/joint_probability_distribution.py:52–68  ·  view source on GitHub ↗

>>> covariance([1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2]) -2.7755575615628914e-17

(
    x_values: list[int],
    y_values: list[int],
    x_probabilities: list[float],
    y_probabilities: list[float],
)

Source from the content-addressed store, hash-verified

50
51# Function to calculate the covariance
52def covariance(
53 x_values: list[int],
54 y_values: list[int],
55 x_probabilities: list[float],
56 y_probabilities: list[float],
57) -> float:
58 """
59 >>> covariance([1, 2], [-2, 5, 8], [0.7, 0.3], [0.3, 0.5, 0.2])
60 -2.7755575615628914e-17
61 """
62 mean_x = expectation(x_values, x_probabilities)
63 mean_y = expectation(y_values, y_probabilities)
64 return sum(
65 (x - mean_x) * (y - mean_y) * px * py
66 for x, px in zip(x_values, x_probabilities)
67 for y, py in zip(y_values, y_probabilities)
68 )
69
70
71# Function to calculate the standard deviation

Calls 1

expectationFunction · 0.85

Tested by

no test coverage detected