"""Simulated readings of one table's length: random scatter, a hidden systematic offset, and how the uncertainty of the average shrinks with the number of readings.""" import sys from pathlib import Path import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from labkit import versions # noqa: E402 SEED = 1729 TRUE_MM = 1523.0 # the table's true length SCATTER_MM = 4.0 # random error of one reading (standard deviation) OFFSET_MM = 2.0 # systematic error: a tape whose zero sits 2 mm short print(f"simulated: seeded random model (numpy default_rng, seed {SEED}); {versions()}") print(f"true length {TRUE_MM:.1f} mm; each reading = true + {OFFSET_MM:.1f} mm offset + random scatter of {SCATTER_MM:.1f} mm") print() rng = np.random.default_rng(SEED) readings = TRUE_MM + OFFSET_MM + rng.normal(0.0, SCATTER_MM, size=10_000) print("The first ten readings (mm):") print(" " + " ".join(f"{r:.0f}" for r in readings[:10])) print() print(" N average (mm) standard deviation (mm) uncertainty of average (mm)") for n in (10, 100, 1_000, 10_000): sample = readings[:n] mean = sample.mean() sd = sample.std(ddof=1) print(f"{n:>6} {mean:>12.2f} {sd:>23.2f} {sd / np.sqrt(n):>27.2f}") print() print(f"The average settles on {readings.mean():.1f} mm, not the true {TRUE_MM:.1f} mm:") print("more readings shrink the random error, never the systematic one.") print() edges = np.arange(1509, 1539, 3.0) counts, _ = np.histogram(readings[:1_000], bins=edges) print("Histogram of the first 1,000 readings (3 mm bins):") for lo, count in zip(edges[:-1], counts): print(f" {lo:.0f}-{lo + 3:.0f} {count:>4} {'#' * (count // 8)}")