Implementation
This page describes the internal flow of covariance and the order in which separate validation of x and y, shape compatibility checks, optional weight validation, and the final covariance calculation on centered data are applied. Unlike Overview, the goal here is not to repeat the parameters, but to show how the function actually builds the result.
The following snippets are taken from the current src/mespy/stats_utils.py implementation. Private helpers are mentioned only to clarify the flow; complete details are documented in _as_float_vector and _validate_weights.
Execution sequence
The implementation follows this sequence:
Converts
xandyinto one-dimensional, finitefloat64vectors.Checks that the two vectors have the same shape.
If
wis provided, it validates it against the shape ofx.If
w is None, uses unit weights, so both branches share the same computation.Centers
xandyby subtracting their respective means (weighted ifwis given).Returns the weighted sum of the products of the deviations, with the two-pass correction term, divided by
sum(w).
Input validation and centering
def covariance(x: ArrayLike, y: ArrayLike, w: ArrayLike | None = None) -> float:
x_values = _as_float_vector("x", x)
y_values = _as_float_vector("y", y)
if x_values.shape != y_values.shape:
raise ValueError("x and y must have the same length")
weights = _validate_weights(x_values, w)
if weights is None:
weights = np.ones_like(x_values)
w_sum = float(np.sum(weights))
dx = x_values - float(np.sum(weights * x_values) / w_sum)
dy = y_values - float(np.sum(weights * y_values) / w_sum)
return float(
(
np.sum(weights * dx * dy)
- np.sum(weights * dx) * np.sum(weights * dy) / w_sum
)
/ w_sum
)
The first part of the flow is entirely dedicated to putting x and y on the same numeric footing.
The two inputs are validated separately, so both must be one-dimensional, non-empty, and composed of finite values.
Only after this normalization does the function check that
x_values.shape == y_values.shape.If the vectors are not compatible, the calculation does not even start.
Implemented formula
The function computes
with \(w_i = 1\) (and therefore \(\sum_i w_i = n\)) in the unweighted case. Mathematically it equals the identity \(E[xy] - E[x]E[y]\), but numerically it does not.
Numerical stability
The identity \(E[xy] - E[x]E[y]\) subtracts two large, nearly equal quantities when the data have an offset that is large compared with their spread: with \(x \approx 10^{15}\) both terms are about \(10^{15} \cdot E[y]\) and the difference loses almost all significant digits (catastrophic cancellation).
Centering the data first makes the products \(d^x_i d^y_i\) the size of the spread, and the cancellation disappears. The correction term
is zero in exact arithmetic and compensates for the rounding error of the means (corrected two-pass formula of Chan, Golub, and LeVeque).
The remaining limit is representation: if the differences between data points are smaller than the ulp of the offset, the information is already lost in float64 before the call.
Important interactions and explicit limits
Some implementation choices are worth making explicit.
The function does not introduce a
ddofparameter: it always normalizes bynor bysum(w).The same weights are used for both means and for the final sum; there are no separate weights for
xandy.If
w is None, the flow does not go throughweighted_mean(...): it uses unit weights and the same code as the weighted branch.If
wis given, the code does not normalize it beforehand; it uses the implicit normalization from dividing bysum(w).Errors from non-finite values or non-positive weights are caught before the computation, so the function never silently returns a
nancovariance.
Commented example
from mespy import covariance
x = [1.0, 2.0, 3.0]
y = [2.0, 4.0, 6.0]
w = [1.0, 1.0, 2.0]
print(covariance(x, y)) # medie semplici
print(covariance(x, y, w)) # medie pesate
The two calls share the same formula, but differ in how the means and the final normalization are built.
Without weights, every point contributes equally.
With
w, all contributions go through the same weighted normalization.