Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Variance from a Distribution

~10 mincode completion

Variance measures spread: the expected squared distance from the mean.

Squaring does two jobs. It makes every deviation positive so they cannot cancel, and it punishes far-away outcomes far more than near ones — which is exactly the behaviour that makes squared error sensitive to outliers.

values = [0, 10]   probs = [0.5, 0.5]
mu  = 5.0
Var = 0.5*(0-5)^2 + 0.5*(10-5)^2 = 25.0

There is a second formula, , which is algebraically identical and numerically worse: with large values the two terms are nearly equal and subtracting them loses precision. Use the definition.

Your task:

Implement distribution_variance(values, probs) returning as a float.

Compute the mean first, then the weighted mean of the squared deviations.

Example Tests

Two equally likely outcomes five either side of the mean

Input: {"probs":[0.5,0.5],"values":[0,10]}

Expected: 25

A lopsided distribution has a mean of 2.5 and variance 18.75

Input: {"probs":[0.75,0.25],"values":[0,10]}

Expected: 18.75

No spread at all means zero variance

Input: {"probs":[0.2,0.3,0.5],"values":[4,4,4]}

Expected: 0

Python
import numpy as np


def distribution_variance(values, probs):
    """
    Variance of a discrete distribution.

    Args:
        values: array of outcomes, shape (n,)
        probs:  array of probabilities, shape (n,), summing to 1

    Returns:
        float: sum of p_i * (x_i - mu)^2
    """
    # YOUR CODE HERE
    pass
Loading docs…