POSTERIOR_WMEANVAR

This function computes weighted posterior moments for a discrete approximation to a posterior distribution or weighted posterior samples.

Given values x_i and nonnegative weights w_i, normalized weights are:

\tilde{w}_i = \frac{w_i}{\sum_j w_j}

The posterior weighted mean and variance are:

\mu = \sum_i \tilde{w}_i x_i, \qquad \sigma^2 = \sum_i \tilde{w}_i (x_i - \mu)^2

The function also reports posterior standard deviation and effective sample size based on normalized weights.

Excel Usage

=POSTERIOR_WMEANVAR(values, weights)
  • values (list[list], required): 2D array of posterior support values.
  • weights (list[list], optional, default: null): 2D array of nonnegative posterior weights aligned with values.

Returns (list[list]): 2D table of weighted posterior summary metrics and values.

Example 1: Unweighted posterior moments from a symmetric support

Inputs:

values
1 2 3 4

Excel formula:

=POSTERIOR_WMEANVAR({1,2,3,4})

Expected output:

Metric Value
Mean 2.5
Variance 1.25
StdDev 1.11803
EffectiveSampleSize 4
Example 2: Weighted posterior mean shifts toward larger support values

Inputs:

values weights
1 2 3 4 1 1 2 4

Excel formula:

=POSTERIOR_WMEANVAR({1,2,3,4}, {1,1,2,4})

Expected output:

Metric Value
Mean 3.125
Variance 1.10938
StdDev 1.05327
EffectiveSampleSize 2.90909
Example 3: Matrix-shaped values and weights are flattened consistently

Inputs:

values weights
0 1 1 2
2 3 3 4

Excel formula:

=POSTERIOR_WMEANVAR({0,1;2,3}, {1,2;3,4})

Expected output:

Metric Value
Mean 2
Variance 1
StdDev 1
EffectiveSampleSize 3.33333
Example 4: Scalar posterior support with implicit unit weight

Inputs:

values
5

Excel formula:

=POSTERIOR_WMEANVAR(5)

Expected output:

Metric Value
Mean 5
Variance 0
StdDev 0
EffectiveSampleSize 1

Python Code

import numpy as np

def posterior_wmeanvar(values, weights=None):
    """
    Compute posterior weighted mean and variance summaries from values and weights.

    See: https://en.wikipedia.org/wiki/Weighted_arithmetic_mean

    This example function is provided as-is without any representation of accuracy.

    Args:
        values (list[list]): 2D array of posterior support values.
        weights (list[list], optional): 2D array of nonnegative posterior weights aligned with values. Default is None.

    Returns:
        list[list]: 2D table of weighted posterior summary metrics and values.
    """
    try:
        def to2d(v):
            return [[v]] if not isinstance(v, list) else v

        values = to2d(values)
        weights = None if weights is None else to2d(weights)

        if not isinstance(values, list) or not all(isinstance(row, list) for row in values):
            return "Error: values must be a 2D list"

        val_flat = []
        for row in values:
            for value in row:
                try:
                    val_flat.append(float(value))
                except (TypeError, ValueError):
                    continue

        if len(val_flat) == 0:
            return "Error: values must contain at least one numeric value"

        val_arr = np.array(val_flat, dtype=float)

        if weights is None:
            weight_arr = np.ones_like(val_arr)
        else:
            if not isinstance(weights, list) or not all(isinstance(row, list) for row in weights):
                return "Error: weights must be a 2D list"

            weight_flat = []
            for row in weights:
                for value in row:
                    try:
                        weight_flat.append(float(value))
                    except (TypeError, ValueError):
                        continue

            if len(weight_flat) != len(val_flat):
                return "Error: weights must contain the same number of numeric entries as values"

            weight_arr = np.array(weight_flat, dtype=float)

        if np.any(weight_arr < 0):
            return "Error: weights must be nonnegative"

        total_weight = float(np.sum(weight_arr))
        if total_weight <= 0:
            return "Error: sum of weights must be positive"

        norm_weights = weight_arr / total_weight
        mean_val = float(np.sum(norm_weights * val_arr))
        var_val = float(np.sum(norm_weights * (val_arr - mean_val) ** 2))
        std_val = float(np.sqrt(var_val))
        ess_val = float(1.0 / np.sum(norm_weights ** 2))

        return [
            ["Metric", "Value"],
            ["Mean", mean_val],
            ["Variance", var_val],
            ["StdDev", std_val],
            ["EffectiveSampleSize", ess_val]
        ]
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

2D array of posterior support values.
2D array of nonnegative posterior weights aligned with values.