Converting the Mean Is Not the Mean of Converted Values

Take two invented readings, 0 and 2. Their mean is 1. If the conversion squares its input, converting that mean gives 1, while converting the readings first and then averaging gives 2. The same records, with no measurement noise added, produce two different answers because the order of operations changed.

This paper-and-code experiment lets you calculate that difference exactly. A mean is the sum of the supplied values divided by their count. A mapping is a rule that assigns an output to each permitted input. Our only nonlinear mapping is F(x)=x² for 0≤x≤2; nonlinear here means it is not a straight-line rule of the form ax+b. Every value is dimensionless: it is a number without a physical unit such as volts or degrees Celsius.

What you need and what to predict

Use paper, a pencil and a computer with Python 3.9 or later. The delivered model and tests use only Python's standard library. CPython, Python's reference implementation, was used for the recorded host runs. No electronics, external service or optional numerical package is required. The reader includes mean_order.py, its behavior tests, the exact records and the figure generator.

Before running anything, write predictions for both routes on the pair [0,2], then repeat for [1,1]. A control is a deliberately chosen comparison that isolates a cause. Identical inputs remove spread; a straight-line mapping removes the nonlinearity. Neither control requires a real sensor.

Follow both routes through one group

Let N be the number of complete supplied records and let μ (mu) be their arithmetic mean. Route A first computes μ and returns F(μ)=μ². Route B returns the mean of the individually mapped outputs, (x₁²+…+xₙ²)/N. Define the route gap as Route B minus Route A, in that order. We treat the entire supplied finite group as the population being described; we are not estimating an unseen population's variance.

Constructed groupμF(μ)mean F(x)Gap
0, 21121
1, 11110
0.5, 1.5111.250.25
0, 1, 2115/32/3
Calculated square curve on x from zero to two, with mapped endpoint samples, F of the mean at one, and the mean mapped output at two.
Original constructed graph. The midpoint of the dashed chord joins the mapped samples; it is a computed average, not a third observation. The orange vertical interval is the route gap. Full-size PNG (Portable Network Graphics) · Editable SVG (Scalable Vector Graphics).

Derive the exact gap

Population variance is the mean squared distance of each member of this complete group from its mean. Its divisor is N, including when N=1. The N−1 formula used to estimate an unseen population variance from a random sample is a different calculation. Here the variance is exactly the missing piece between the two routes:

variance = Σ(xᵢ−μ)²/N = Σxᵢ²/N − 2μ(Σxᵢ/N) + μ² = mean F(x) − μ². The symbol Σ (sigma) means to add the expression for every member. Because Σxᵢ/N=μ, the middle terms reduce to −2μ²+μ². Therefore gap=population variance≥0. This is an algebraic identity for the declared square rule, not a statistical confidence claim.

All input and output values here are dimensionless. In a real physical model, squaring a voltage produces squared-voltage units unless a stated coefficient or reference scale changes them; blindly copying this rule into an instrument would lose that dimensional meaning. The identity alone supplies no such physical model.

For a second control use G(x)=2x+3, an affine mapping: a scaled input plus a constant offset. Its two routes agree because mean(2x+3)=2mean(x)+3. This holds even when the original records are spread out. It does not require their variance to vanish.

Run the complete experiment

  1. Extract the reader archive into one directory. Open standalone-preview.html for this article and keep the file tree intact. From a terminal in that directory run the commands below. A command-line interface (CLI) is a program operated by typed commands.
  2. Run the tests, then analyze data/constructed-records.json. The file uses JavaScript Object Notation (JSON), a text format for named fields and lists. Decimal numbers are deliberately strings, for example "0.1". A rational number is an exact ratio of integers; Python's Fraction preserves those finite decimal inputs exactly.
  3. Compare the endpoints, constant and narrow groups with the table. The result's F_mean is Route A, mean_F is Route B, and gap must match population_variance. A printed 2/3 is an exact fraction, not a rounded decimal.
  4. Run the blank template. Its observations and calculated results remain null, meaning unknown. Do not replace an unmade observation with zero. A partly filled group also remains unknown rather than silently dropping its missing member.
  5. Run the supplied malformed file. It must exit with code 2 and an error on the error stream, with no result on the ordinary output stream. Restore the original constructed file and rerun it; the endpoint gap must return to 1.
python3 -B -m unittest -v test_mean_order
python3 -B mean_order.py data/constructed-records.json
python3 -B mean_order.py data/blank-observations.json
python3 -B mean_order.py data/malformed-records.json
python3 -B mean_order.py data/constructed-records.json
python3 -B generate_figures.py

The recorded host run passed 27 behavior tests. The endpoint result is exactly mean_x="1", F_mean="1", mean_F="2", gap="1", population_variance="1". The malformed file contains "NaN" (not a number), which is rejected. The blank result is unknown, with no computed mean or gap. These are software executions on supplied records, not physical observations.

Vary spread while keeping the mean fixed

The file data/spread-records.json supplies eleven pairs 1−δ and 1+δ, where δ (delta) runs from 0 to 1 in steps of 0.1. δ is the pair's half-spread: half the difference between its larger and smaller input. Each pair has μ=1. Substituting the two values gives mean F(x)=1+δ², so the gap is δ². The generator runs the delivered model and writes the plotted exact values to data/spread-figure-data.csv; CSV means comma-separated values, a text table with one record per line.

Calculated route-gap graph for eleven constructed pairs with mean one: square-map gap rises as half-spread squared, while affine-control gap stays zero.
Original calculated spread graph, not measured noise. Orange dots come from the exact delivered records; the blue curve is the derived δ² identity. Green diamonds show the affine control's zero gap. Full-size PNG · Editable SVG.

The generator uses the standard library to recreate both SVGs. Rendering PNGs is optional: with the resvg_py renderer installed, run python3 -B generate_figures.py --png. The existing PNGs are included; the model and learner tests do not need that renderer.

Complete model

The model validates the whole group before calculating either route. It rejects duplicate group identifiers, repeated sample identifiers within a group, duplicate JSON field names, extra or missing fields, non-decimal strings, nonfinite values and inputs outside [0,2]. Equal numerical values with different sample identifiers are valid repeated values, not duplicate records. Limits are 128 groups, 256 samples per group, 40 characters per decimal and 1,000,000 input bytes. Decimal exponent notation is intentionally unsupported.

Identifiers use the American Standard Code for Information Interchange (ASCII) character subset shown in the program.

Full mean_order.py source
#!/usr/bin/env python3
"""Exact constructed F(x)=x*x experiment. No real sensor calibration."""
import argparse
from fractions import Fraction
import json
from pathlib import Path
import re
import sys

MAX_BYTES = 1_000_000
MAX_GROUPS = 128
MAX_SAMPLES = 256
DECIMAL = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)\Z")
IDENTIFIER = re.compile(r"[A-Za-z0-9_-]{1,40}\Z")
FIELDS = ("mean_x", "F_mean", "mean_F", "gap", "population_variance",
          "G_mean", "mean_G", "affine_gap")


def parse_value(value):
    """Return exact Fraction or None. Reject missing-format/nonfinite/range faults."""
    if value is None:
        return None
    if not isinstance(value, str) or len(value) > 40 or not DECIMAL.fullmatch(value):
        raise ValueError("x must be null or a finite decimal string (40 chars max)")
    number = Fraction(value)
    if not 0 <= number <= 2:
        raise ValueError("x outside supported dimensionless interval [0,2]")
    return number


def exact(value):
    return str(value.numerator) if value.denominator == 1 else str(value)


def keys(record, expected, label):
    if not isinstance(record, dict) or set(record) != set(expected):
        raise ValueError(label + " has missing/extra fields")


def identifier(value):
    if not isinstance(value, str) or not IDENTIFIER.fullmatch(value):
        raise ValueError("identifier must be 1..40 ASCII letters/digits/_/-")
    return value


def analyze(document):
    keys(document, ("kind", "groups"), "document")
    if document["kind"] not in ("constructed", "observation_blank"):
        raise ValueError("kind must be constructed or observation_blank")
    groups = document["groups"]
    if not isinstance(groups, list) or not 1 <= len(groups) <= MAX_GROUPS:
        raise ValueError("need 1..128 groups")
    output, seen_groups = [], set()
    for group in groups:
        keys(group, ("group_id", "samples"), "group")
        group_id = identifier(group["group_id"])
        if group_id in seen_groups:
            raise ValueError("duplicate group_id")
        seen_groups.add(group_id)
        samples = group["samples"]
        if not isinstance(samples, list) or len(samples) > MAX_SAMPLES:
            raise ValueError("samples must be a list with at most 256 entries")
        values, seen_samples = [], set()
        for sample in samples:
            keys(sample, ("sample_id", "x"), "sample")
            sample_id = identifier(sample["sample_id"])
            if sample_id in seen_samples:
                raise ValueError("duplicate sample_id within group")
            seen_samples.add(sample_id)
            values.append(parse_value(sample["x"]))
        if document["kind"] == "observation_blank" and any(v is not None for v in values):
            raise ValueError("blank observation template cannot contain invented values")
        row = {"group_id": group_id, "count": len(values),
               "known_count": sum(v is not None for v in values)}
        if not values or any(v is None for v in values):
            row.update(status="unknown", reason="empty group or missing observation")
            row.update({field: None for field in FIELDS})
        else:
            n = len(values)
            mu = sum(values, Fraction(0)) / n
            mean_f = sum((v*v for v in values), Fraction(0)) / n
            variance = sum(((v-mu)**2 for v in values), Fraction(0)) / n
            g_mean = 2*mu + 3
            mean_g = sum((2*v+3 for v in values), Fraction(0)) / n
            answers = (mu, mu*mu, mean_f, mean_f-mu*mu, variance,
                       g_mean, mean_g, mean_g-g_mean)
            row.update(status="computed_constructed")
            row.update({field: exact(value) for field, value in zip(FIELDS, answers)})
        output.append(row)
    return {"kind": document["kind"], "units": "dimensionless",
            "arithmetic": "exact rational from finite decimal strings",
            "variance_divisor": "N (complete supplied group, not N-1 estimator)",
            "groups": output}


def no_duplicate_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("duplicate JSON key: " + key)
        result[key] = value
    return result


def loads_strict(text):
    return json.loads(text, object_pairs_hook=no_duplicate_keys,
                      parse_constant=lambda token: (_ for _ in ()).throw(
                          ValueError("nonfinite JSON constant: " + token)))


def read_document(path):
    with Path(path).open("rb") as stream:
        raw = stream.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ValueError("input exceeds 1000000 bytes")
    return loads_strict(raw.decode("utf-8"))


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", help="strict JSON constructed records or blank template")
    args = parser.parse_args(argv)
    try:
        answer = analyze(read_document(args.input))
    except (ValueError, OSError, UnicodeError) as error:
        print("error: " + str(error), file=sys.stderr)
        return 2
    print(json.dumps(answer, indent=2, allow_nan=False))
    return 0


if __name__ == "__main__":
    sys.exit(main())

Faults, restoration and what you can conclude

Copy the endpoint file before changing it. Replace one "2" with null: both routes become unknown. Replace it with "2.01": validation fails, because the declared domain ended at 2. Duplicate a sample's identifier: validation fails before averages are formed. Move the original records into the opposite order: the answer stays the same. Restore the original file after every fault and check the endpoint gap of 1. Do not relabel any of these constructed inputs as collected measurements.

The controls show that spread and the nonlinear mapping jointly matter in this example. They do not establish a universal processing order for instruments. If the desired quantity is the mean of individual squared values, Route B directly calculates it. If the desired quantity is the square of the mean input, Route A directly calculates that other quantity. A measurand is the quantity intended to be measured; deciding it comes before choosing an estimator or a calibration workflow. Real sensor transfer functions, correlated errors, drift, saturation and uncertainty require their own models and evidence.

Challenge: predict a new pair before running it

For [0.25,1.75], μ=1 and δ=0.75. Predict both routes and the affine result. Then create a new constructed group with distinct sample identifiers.

Answer: F(μ)=1, mean F(x)=25/16, gap=9/16, population variance=9/16. Both affine routes equal 5. Changing the number of repeated copies of both values equally leaves these descriptive quantities unchanged.

Further reading and files

Wang and Iyer, On Non-Linear Estimation of a Measurand, National Institute of Standards and Technology (NIST), compares nonlinear estimation routes and cautions against a uniformly preferred method. Its abstract supplies that scope point; the finite square identity here is derived above. OpenStax, Measures of the Spread of the Data, distinguishes the population N divisor from the sample-estimator N−1 divisor. Neither source is reproduced in the reader.

The related experiment More Readings Do Not Remove One Shared Offset studies dependence between readings. This article isolates a different issue: changing the order of a nonlinear mapping and a mean, even for exact invented numbers.

Use the model, the behavior tests, the figure generator, constructed records, blank observations, and the source index. The explanatory text remains Hypertext Markup Language (HTML), so it can be searched and copied independently of the figures.