On this page Execution sequence

API Reference / mespy.variance

Implementation

This page describes the internal flow of variance and the order in which input validation, selection of the unweighted or weighted branch, denominator checks, and final squared-deviation calculation are applied. Unlike Overview, the goal here is not to repeat the signature, but to show how the function actually builds the variance.

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:

  1. Converts x into a one-dimensional, finite float64 vector.

  2. If w is provided, it validates it as a compatible vector with strictly positive values and positive sum.

  3. If w is None, it uses the unweighted branch with denominator len(x) - ddof.

  4. If w is provided, it uses the weighted branch with denominator sum(w) - ddof.

  5. In both branches it checks the denominator right away: if it is less than or equal to zero, it stops the calculation with ValueError.

  6. It computes the mean consistent with the selected branch, then the corrected sum of squared deviations divided by the denominator.

Unweighted and weighted branches

def variance(x: ArrayLike, w: ArrayLike | None = None, ddof: int | float = 0) -> float:
    values = _as_float_vector("x", x)
    weights = _validate_weights(values, w)

    if weights is None:
        n = values.size
        denom = n - ddof
        if denom <= 0:
            raise ValueError(f"non-positive denominator: len(x) - ddof = {n} - {ddof}")

        dx = values - float(np.mean(values))
        return float((np.sum(dx * dx) - np.sum(dx) ** 2 / n) / denom)

    w_sum = float(np.sum(weights))
    denom = w_sum - ddof
    if denom <= 0:
        raise ValueError(f"non-positive denominator: sum(w) - ddof = {w_sum} - {ddof}")

    dx = values - float(np.sum(weights * values) / w_sum)
    return float(
        (np.sum(weights * dx * dx) - np.sum(weights * dx) ** 2 / w_sum) / denom
    )

The core of the function is the clear separation between two operational definitions of variance.

  • In the unweighted case the effective cardinality is n = values.size.

  • In the weighted case the normalization quantity becomes w_sum = sum(weights).

  • In both cases ddof acts by subtracting a correction from the denominator, but the base it applies to changes.

Implemented formulas

In the unweighted branch the function uses

\[\bar{x} = \frac{1}{n}\sum_i x_i, \qquad \mathrm{Var}(x) = \frac{\sum_i (x_i - \bar{x})^2}{n - \mathrm{ddof}}.\]

In the weighted branch it instead uses

\[\bar{x}_w = \frac{\sum_i w_i x_i}{\sum_i w_i}, \qquad \mathrm{Var}_w(x) = \frac{\sum_i w_i (x_i - \bar{x}_w)^2}{\sum_i w_i - \mathrm{ddof}}.\]

The function does not delegate to numpy.var(...): it explicitly builds the mean consistent with the selected branch and then sums the squared deviations.

Numerical stability

The code does not sum \((x_i - \bar{x})^2\) directly, but uses the corrected two-pass formula (Chan, Golub, LeVeque):

\[\sum_i w_i d_i^2 - \frac{\left(\sum_i w_i d_i\right)^2}{\sum_i w_i}, \qquad d_i = x_i - \bar{x}_w,\]

with \(w_i = 1\) in the unweighted branch. In exact arithmetic \(\sum_i w_i d_i = 0\), so the subtracted term is zero and the definition stays the one written above.

In floating point the computed mean has a rounding error \(\delta\) which, for data with a large offset (for example \(x \approx 10^{15}\)), is about one ulp of the offset. Summing only the squared deviations lets that error enter the result as \(+\delta^2\); the correction term removes it.

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 and no algorithm can recover it.

Role of ddof and error conditions

The ddof parameter does not only change the statistical interpretation of the result: it can make the computation impossible.

  • In the unweighted case the code requires len(x) - ddof > 0.

  • In the weighted case it requires sum(w) - ddof > 0.

  • If one of these conditions fails, the function raises ValueError before performing the final division.

The default ddof=0 is consistent with the descriptive setup of the package: by default the function computes a population variance, not the version with Bessel’s correction.

Important interactions between parameters

Some aspects of the behavior are worth making explicit.

  • w=None does not mean “all weights equal” implemented by hand: it explicitly means using the unweighted branch based on np.mean(values).

  • If all weights are equal and ddof=0, the value matches a variance computed with uniform weights, but the denominator in the weighted branch remains sum(w), not len(x).

  • The function also accepts ddof as a float, so the correction is not limited to integers.

  • Errors from empty, non-one-dimensional, or non-finite inputs are always caught at the start by _as_float_vector, while errors specific to the weighted branch go through _validate_weights.

Commented example

from mespy import variance

x = [1.0, 2.0, 3.0]
w = [1.0, 1.0, 2.0]

print(variance(x))  # ramo non pesato
print(variance(x, w=w))  # ramo pesato
print(variance(x, ddof=1))

In this example the same function is used in three different ways.

  • The first call uses n - ddof with ddof=0.

  • The second instead uses sum(w) - ddof, so the normalization depends on the weights.

  • The third keeps the unweighted case but applies an explicit correction to the denominator.