Measurement records · complete offline experiment

A Burst of Readings Can Shift a Voltage Average

Add nine readings without changing the declared voltage trace. The ordinary average moves upward, while the duration-weighted answer stays fixed. Use timestamps to find out which question your average actually answers.

Verification scope: All example records and plots are synthetic, meaning constructed by the supplied code. No sensor, voltage source or microcontroller was connected or measured. The complete program and its host tests run on a normal computer; no physical result or target firmware build is claimed.

Choose the quantity before choosing the average

An arithmetic mean adds the recorded values and divides by their count. Call this the row mean: every row has equal weight, the share it contributes to the answer. A time average instead asks how much of an observation period the signal spends at each value. A logger that records rapidly during one part of a period gives that part many rows, even if it occupies little time.

Neither calculation supplies its purpose automatically. The row mean describes the recorded values. To describe the signal over time, you need timestamps and a statement about the signal between them. A timestamp is a number identifying when a recorded observation or command belongs. This lesson uses elapsed time in seconds (s) and voltage in volts (V).

Use a computer with Python 3.9 or later and a text editor. The delivered host checks ran on Python 3.9.6 with its standard library, the modules supplied with Python. No additional library, circuit, pin connection or electrical supply is needed. The examples use comma-separated values (CSV), a plain-text table with one record on each line.

Declare one held trace, then log it two ways

For this constructed experiment, declare that a command value is held at 1 V from time 0 up to time 9 s, then at 3 V from 9 s through the end of the 10 s window. “Held” means the value remains constant until the next command changes it. The ideal jump is a rule for these numbers; it is not a claim that a physical voltage source changes instantaneously.

The sparse record contains three rows:

t_s,voltage_v
0,1
9,3
10,3

Its row mean is (1 + 3 + 3)/3 = 7/3 ≈ 2.333 V. Now insert nine more rows at 9.1, 9.2, …, 9.9 s, all with value 3 V. The resulting burst record has twelve rows: one value of 1 V and eleven values of 3 V. Its row mean becomes (1 + 11 × 3)/12 = 34/12 ≈ 2.833 V.

The declared trace did not change. Only its row density changed. The same nine seconds at 1 V and one second at 3 V still occupy the ten-second window. For that known held trace, the time average is:

(1 V × 9 s + 3 V × 1 s) / 10 s = 12 V·s / 10 s = 1.2 V.

One synthetic held voltage trace stays at 1 V for 9 s and 3 V for 1 s. Sparse and burst timelines place 3 and 12 rows on that same trace; row means change from 2.333 V to 2.833 V while the hold-model time average remains 1.2 V.
Figure 1. Original calculated trace and row-position diagrams. The hollow point marks the excluded lower value at the jump; the filled point is the value at 9 s. All examples are constructed. Editable Scalable Vector Graphics (SVG) original · Full-size Portable Network Graphics (PNG) image.

A row at the final timestamp closes the window. It has no interval after it inside this record. It counts once in the diagnostic row mean, but the hold-model integral assigns it no subsequent duration. This endpoint convention is one reason that even regularly spaced endpoint rows do not generally have the same weights as a duration calculation.

Derive the duration weights

Let the timestamps be t₀, t₁, …, tₙ and their values be v₀, v₁, …, vₙ. There are n + 1 rows and n intervals between them. Define Δtᵢ = tᵢ₊₁ − tᵢ, the duration of interval i, and T = tₙ − t₀, the total recorded span. The symbol Σ below means add the indicated interval contributions.

Under the hold model, row i applies on [tᵢ, tᵢ₊₁): the left endpoint is included and the right endpoint is excluded. The next row starts the next interval. Each interval contributes a rectangle with height vᵢ and width Δtᵢ to the area under the voltage-versus-time graph:

Ihold = Σ vᵢΔtᵢ; Vtime,hold = Ihold / T.

An integral adds these contributions over the window. Here its unit is volt-seconds, written V·s. Dividing by seconds returns volts. A volt-second integral is not electrical energy; finding energy would require a power quantity, such as voltage multiplied by current, before integrating.

The National Institute of Standards and Technology (NIST) Dataplot weighted-mean reference, equations 2-19 and 2-20, distinguishes equal row weights from general weights. This experiment uses interval durations as the weights for an explicitly held path. It does not use inverse-uncertainty weights or infer that the observations are statistically independent.

The same rows can support a different assumed path

Interpolation supplies a value between recorded points using a chosen rule. Under linear interpolation, a straight line joins each adjacent pair. Its interval area is a trapezoid, a four-sided shape whose two parallel sides have heights vᵢ and vᵢ₊₁. The interval’s average height is their arithmetic mean:

Ilinear = Σ [(vᵢ + vᵢ₊₁)/2]Δtᵢ; Vtime,linear = Ilinear / T.

For the sparse record, the first segment rises from 1 V to 3 V over nine seconds. Its area is 9 × (1 + 3)/2 = 18 V·s. The final one-second segment stays at 3 V and adds 3 V·s. The result is 21 V·s / 10 s = 2.1 V. This answers the question for the straight-line path. Our declared held command gives 1.2 V because it specifies a different path.

The NIST Digital Library of Mathematical Functions (DLMF), equation 3.5.1, gives the elementary trapezoidal rule and a curvature-dependent error term for sufficiently smooth functions. We apply the area formula separately to each interval. It is exact for each chosen straight segment apart from numerical rounding. We do not borrow the smooth-function error guarantee for the discontinuous held command or an unknown sensor signal.

The same three synthetic rows are joined as a hold path on the left and a linear path on the right. Shaded areas are 12 and 21 volt-seconds over the same 10 s window; dashed model-average lines lie at 1.2 and 2.1 V.
Figure 2. Original constructed path and area comparison. The dots agree; the assumptions between them differ. The dashed lines show each model’s time average. Editable SVG · Full-size PNG.

If these were only three sensor observations, the values alone would not prove that the signal stayed flat or followed a straight line. A short unobserved pulse could change the actual area. A real command log would also need trustworthy update times and evidence of what the hardware actually did; a timestamp recorded when software requested a change is not automatically that evidence. The synthetic held command is known here because we declared it.

Run the complete experiment

Extract the reader contents and reproduction instructions, preserving the relative folders. The sparse, burst and regular CSV files are supplied. The regular record has 101 rows spaced 0.1 s apart; every row comes from the same declared held trace. Run these commands from the extracted directory:

python3 -m unittest discover -s code -p 'test_*.py'
python3 code/time_average.py summary data/synthetic-sparse.csv --method hold --max-gap-s 10
python3 code/time_average.py summary data/synthetic-burst.csv --method hold --max-gap-s 10
python3 code/time_average.py summary data/synthetic-sparse.csv --method linear --max-gap-s 10
python3 code/time_average.py summary data/synthetic-regular.csv --method hold --max-gap-s 0.11
python3 code/time_average.py demo new-demo-directory

The output is JavaScript Object Notation (JSON), a text format that groups named values and lists. The program reports row mean, selected model, integral, total span, largest gap and every interval’s contribution. The supplied comparison summary gives these calculated results:

RecordRowsRow meanHold time meanLinear time mean
Sparse32.333333 V1.200000 V2.100000 V
Burst122.833333 V1.200000 V2.100000 V
Regular1011.217822 V1.200000 V1.210000 V

Adding rows on the constant 3 V segment leaves both model integrals unchanged. In the regular record, linear interpolation replaces the known jump by a short ramp between the 8.9 s and 9.0 s observations. Its result is closer to the held result than the sparse linear estimate, but still represents a different path. More rows can constrain an assumed path without proving what happened between observations.

  1. Run the three sparse/burst commands and check the analytic values above. Save the outputs. Add another 3 V row at 9.05 s in a copy of the burst file. Verify the row mean changes again while both model integrals remain fixed.
  2. Copy the sparse file and move the 3 V transition row from 9 s to 8 s. Keep the final row at 10 s. Predict both model integrals before running the program; the answer is in the challenge below.
  3. Try --max-gap-s 1 on the original sparse file. The nine-second gap must be refused. The tool does not drop that interval and renormalize the remaining second. Restore a bound of 10 s only for the declared held-command exercise, where the model is known by construction.
  4. Introduce a duplicate timestamp, reverse two rows, erase a voltage cell or type nan, meaning “not a number.” Each record must fail. The tool never sorts or silently skips rows to make a result.
  5. Use --audit-out new-interval-audit.csv to write a fresh per-interval CSV. Check that duration multiplied by the selected interval mean equals its area. The output file must not already exist. Use the blank record-review worksheet to record assumptions and results; it is not a measurement log.

Set a gap policy before trusting a record

A gap is the time between adjacent timestamps. The required --max-gap-s value is a caller-supplied rejection policy. For an actual application, choose it from the required observation coverage and relevant signal behavior before interpreting the result. Raising it merely to pass a failed record does not establish missing signal history.

A small maximum gap can still hide a faster event. A quantitative integration-error bound needs additional information, such as a justified limit on signal curvature or a verified held command. The program supplies no uncertainty interval or proof that either path model is true. It covers only the first-to-last timestamp span; extrapolation, extending a model before or after that span, is not performed.

The comparison uses the supplied floating-point timestamps and a strict gap inequality. Floating point stores finite binary approximations to numbers. Choose a bound with a justified margin above ordinary timestamp rounding, rather than setting a policy exactly on a decimal boundary you cannot represent reliably. The worked regular record uses 0.11 s for its nominal 0.1 s gaps. This numerical margin is not a claim that a missing 0.11 s interval is harmless.

Convert time units explicitly. Renaming a millisecond column to t_s without dividing its numbers by 1000 changes the integral, span and gap interpretation. Their common scale factor can cancel in the average, so a plausible voltage answer does not prove correct time units. Use elapsed timestamps from one suitable clock; a clock reset or rollback needs its own record boundary, not a rearrangement of rows.

Full supplied program

The complete executable file is code/time_average.py; the behavioral checks are code/test_time_average.py. The CSV header must be exactly t_s,voltage_v. The reader rejects malformed cells and CSV syntax, nonfinite numbers, fewer than two rows, non-increasing times and intervals exceeding the explicit bound. Arithmetic checks refuse detected overflow or underflow, meaning numbers too large or too small for the implementation’s representable intermediate values. Genuine cancellation to zero is allowed.

The program uses Python’s documented math.fsum to sum contributions and a scaled mean calculation to reduce some avoidable overflow. Its standard CSV reader runs in strict mode. These choices still use rounded floating-point arithmetic; they do not make arbitrary-precision or exact-decimal promises.

#!/usr/bin/env python3
"""Duration-weighted voltage from an explicit hold or linear record model.

Python3.9+, standard library only. CSV: t_s,voltage_v (seconds and volts).
No sorting, skipped rows, gap filling, extrapolation or physical-test claim.
"""
import argparse
import csv
import json
import math
from pathlib import Path


def finite_positive(value, name):
    if not math.isfinite(value) or value <= 0:
        raise ValueError(name+' must be finite and positive')
    return value


def mean(values):
    """Scale before summing so ordinary same-sign values do not overflow."""
    scale=max(abs(v) for v in values)
    if not scale:
        return 0.0
    normalized=[v/scale for v in values]
    if any(v!=0 and term==0 for v,term in zip(values,normalized)):
        raise ValueError('Mean normalization is outside floating-point range')
    total=math.fsum(normalized)
    average=total/len(values)
    if total!=0 and average==0:
        raise ValueError('Normalized mean is outside floating-point range')
    result=scale*average
    if average!=0 and result==0:
        raise ValueError('Mean is outside floating-point range')
    return result


def read_rows(stream):
    reader=csv.reader(stream,strict=True)
    if next(reader,None) != ['t_s','voltage_v']:
        raise ValueError('CSV header must be exactly t_s,voltage_v (seconds, volts)')
    rows=[]
    for number,row in enumerate(reader,2):
        if len(row)!=2:
            raise ValueError('CSV row '+str(number)+' needs exactly two cells')
        try:
            rows.append(tuple(float(value) for value in row))
        except ValueError:
            raise ValueError('CSV row '+str(number)+' contains a nonnumeric cell') from None
    return rows


def analyze(rows, method, max_gap_s):
    """Integrate only [first timestamp,last timestamp] under the stated model.

    hold: voltage at row i applies to [t_i,t_(i+1)).
    linear: connect each adjacent pair by a straight line.
    The final row has no subsequent duration. Neither model is inferred as true.
    """
    if method not in ('hold','linear'):
        raise ValueError('method must explicitly be hold or linear')
    finite_positive(max_gap_s,'max_gap_s')
    if len(rows)<2:
        raise ValueError('At least two rows are required')
    if any(len(row)!=2 or any(not math.isfinite(value)for value in row)for row in rows):
        raise ValueError('Every row needs two finite numbers')
    span=rows[-1][0]-rows[0][0]
    if not math.isfinite(span):
        raise ValueError('Timestamp span must remain finite')
    intervals=[]
    for index,((start,left),(end,right))in enumerate(zip(rows,rows[1:])):
        duration=end-start
        if duration<=0:
            raise ValueError('Timestamps must be strictly increasing; record is not sorted for you')
        if not math.isfinite(duration):
            raise ValueError('Every timestamp interval must remain finite')
        if duration>max_gap_s:
            raise ValueError('Interval '+str(index)+' gap exceeds max_gap_s; no missing area is invented')
        midpoint=left if method=='hold' else mean([left,right])
        area = midpoint * duration
        if not math.isfinite(area) or (area==0 and midpoint!=0):
            raise ValueError('Interval integral is outside floating-point range')
        intervals.append({'index':index,'start_s':start,'end_s':end,'duration_s':duration,
                          'left_v':left,'right_v':right,'interval_mean_v':midpoint,'area_v_s':area})
    try:
        integral=math.fsum(item['area_v_s']for item in intervals)
    except OverflowError:
        raise ValueError('Total integral is outside floating-point range') from None
    average=integral/span
    if not math.isfinite(integral) or not math.isfinite(average) or (average==0 and integral!=0):
        raise ValueError('Result is outside floating-point range')
    return {'row_count':len(rows),'interval_count':len(intervals),'method':method,
            'start_s':rows[0][0],'end_s':rows[-1][0],'span_s':span,
            'largest_gap_s':max(item['duration_s']for item in intervals),'max_gap_s':max_gap_s,
            'row_mean_v':mean([row[1]for row in rows]),'integral_v_s':integral,
            'time_average_v':average,'intervals':intervals,
            'assumption':('Row i voltage holds on [t_i,t_(i+1)); no duration after final row.'
                          if method=='hold' else 'A straight line joins each adjacent pair; no extrapolation.'),
            'limits':'Gap bound is a rejection policy, not a signal-error or uncertainty guarantee. Volt-seconds are not energy.'}


def demo_records():
    """Three synthetic records of one declared held command, never measurements."""
    sparse=[(0.0,1.0),(9.0,3.0),(10.0,3.0)]
    burst=[(0.0,1.0),(9.0,3.0)]+[(9+i/10,3.0)for i in range(1,10)]+[(10.0,3.0)]
    regular=[(i/10,1.0 if i<90 else 3.0)for i in range(101)]
    return {'synthetic-sparse.csv':sparse,'synthetic-burst.csv':burst,'synthetic-regular.csv':regular}


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    sub=parser.add_subparsers(dest='command',required=True)
    summary=sub.add_parser('summary',help='analyze an explicit record model')
    summary.add_argument('csv_path',type=Path)
    summary.add_argument('--method',choices=('hold','linear'),required=True)
    summary.add_argument('--max-gap-s',type=float,required=True)
    summary.add_argument('--audit-out',type=Path,help='write a new per-interval CSV; existing files refused')
    demo=sub.add_parser('demo',help='generate synthetic example records in a new directory')
    demo.add_argument('output_directory',type=Path)
    args=parser.parse_args()
    try:
        if args.command=='summary':
            with args.csv_path.open(newline='')as stream:
                result=analyze(read_rows(stream),args.method,args.max_gap_s)
            if args.audit_out:
                # Exclusive creation also prevents a race with another writer.
                with args.audit_out.open('x',newline='')as stream:
                    writer=csv.DictWriter(stream,fieldnames=list(result['intervals'][0]),lineterminator='\n')
                    writer.writeheader();writer.writerows(result['intervals'])
            print(json.dumps(result,indent=2,allow_nan=False))
        else:
            args.output_directory.mkdir(parents=True,exist_ok=False)
            for name,rows in demo_records().items():
                with (args.output_directory/name).open('x',newline='')as stream:
                    writer=csv.writer(stream,lineterminator='\n');writer.writerow(['t_s','voltage_v']);writer.writerows(rows)
            print('Wrote three synthetic held-command records only.')
    except (ValueError,OSError,csv.Error)as exc:
        parser.exit(2,'Record refused: '+str(exc)+'\n')
    return 0


if __name__=='__main__':
    raise SystemExit(main())

The 27 supplied host tests exercise analytic hold and linear integrals, constant and ramp controls, burst invariance, endpoint behavior, origin shifts, signed cancellation, gap boundaries, missing/bad data, numeric range and actual command-line audit/refusal paths. They also generate and analyze the real supplied demo format. Tests of synthetic numbers do not verify a sensor, a physical waveform, clock accuracy or a target platform.

Challenge and answer

Challenge: Move the sparse transition row from 9 s to 8 s, keeping values 1 V then 3 V and the final row at 10 s. What happens to the row mean, hold time mean and linear time mean? Why are these answers different?

Answer

The three row values are unchanged, so their row mean stays 7/3 ≈ 2.333 V. The held trace spends eight seconds at 1 V and two at 3 V: area 8 + 6 = 14 V·s, mean 1.4 V. The linearly joined first interval has area 8 × (1 + 3)/2 = 16 V·s, followed by 6 V·s, giving 22 V·s / 10 s = 2.2 V. The row mean responds to counts; the time means respond to durations and to their stated between-row paths.

Sources and the next decision

The NIST Dataplot reference supplies the ordinary and weighted-mean formulas; DLMF §3.5(i) supplies the trapezoidal formula and its smoothness-qualified error discussion. The experiment’s durations, held-command contract, generated rows, numerical comparisons and code are original constructed examples. Current official Python documentation was checked for the supplied CSV and summation interfaces. Raw primary snapshots are retained as research evidence outside the public reader archive; official links remain available in the article and source index.

For a separate order-of-operations problem, read Converting the Mean Is Not the Mean of Converted Values. That lesson changes the conversion operation; this one changes how much time each part represents. Continue through Tricky Circuit Learn and Circuitpedia. Candidate terminology in this package has not been added to the live multilingual dictionary. Local source preparation, independent review, browser delivery and publication remain separately evidenced steps.