Standard error of the mean (independent readings)
Here
A report says the cold room held 4.013 °C and that a new door seal lowered the mean by 0.03 °C. Is 0.03 °C a real change or only chance? A report that cannot answer has proved nothing. Logging software often prints a very small range beside a mean because it counts every one-minute reading as separate evidence, but readings one minute apart mostly repeat each other. This lesson shows how to put a range on an average that you can defend in front of a customer, an auditor or your own manager. #EngineeringStatistics #ConfidenceInterval #Autocorrelation
By the end of this lesson, you will be able to:
A cold room for vaccines and dairy products is set to 4 °C. Its thermostat starts the compressor at 5 °C and stops it at 3 °C, so the air temperature rises and falls all day in a saw-tooth pattern. A probe in the return air sends one reading a minute to a logger. After 14 days the logger holds 20,160 readings, and their mean is 4.013 °C.
The site manager wants one line for the quality file: the mean temperature and how sure we are of it. It matters because the next step is a comparison: if the mean after a repair is 3.98 °C, the repair changed something only if the two means differ by more than their uncertainty.
The spreadsheet answer is 4.013 ± 0.009 °C. The probe has a random noise of 0.05 °C and is usually accurate to about ± 0.5 °C, so a range of ± 0.009 °C must be examined before anyone signs it.
The 14 days in the logger are a sample. The manager cares about the long-run mean of the room: the value a very long record would give with the same equipment, use and weather. Another 14 days would give a slightly different sample mean. The uncertainty of an average answers one question: by how much do such sample means differ from each other?
This course writes
The standard deviation
Standard error of the mean (independent readings)
Here
Take 25 spot checks of a room with a hand thermometer, on 25 different days, with
A standard error becomes a range when it is multiplied by a factor that fixes how often the range is right.
Confidence interval of a mean
For 95 percent confidence and a large sample,
The factor is larger for a small sample because
| Readings | Degrees of freedom | |
|---|---|---|
| 3 | 2 | 4.303 |
| 5 | 4 | 2.776 |
| 7 | 6 | 2.447 |
| 10 | 9 | 2.262 |
| 14 | 13 | 2.160 |
| 25 | 24 | 2.064 |
| very many | very many | 1.960 |
For the 25 spot checks, the interval is
The 95 percent describes the method, not one result. Repeat the whole measurement many times, each with a new 14 days and the same rule, and about 95 of every 100 intervals contain the true long-run mean. The other 5 miss it, and nothing in the data tells you which ones. What the interval does not mean:
If the room is at 4.6 °C now, it will be very near 4.6 °C one minute from now, so the second reading adds almost no new information about the mean. It is like asking one person the same question every minute: you hear the same answer sixty times, not sixty opinions.
A signal whose values resemble its own recent past is called autocorrelated. Almost all sensor data is autocorrelated, because physical things have inertia: air, water and metal cannot change temperature in an instant.
The lag-1 autocorrelation
A value near 0 means that neighbouring readings are unrelated. A value near 1 means that each reading almost repeats the last. The cold room data gives
A simple model of a signal with memory says that the autocorrelation falls by the same factor at every step:
Effective sample size (AR(1)-like signal)
With
This method needs no model of the signal. Cut the record into blocks longer than the longest pattern in the data, take the mean of each block, and treat the block means as the readings. If the blocks are long enough, their means are close to independent and the simple rule with the
For most sites the natural block is one day, because working hours, door use and weather all repeat daily. Where weekdays differ from weekends, the natural block is one week. The price is a small number of blocks, so the
Reverse the interval. If the mean must be known within a fraction
The answer counts independent readings. It rises with the square of the scatter and with the square of the precision that is asked for. Application 2 uses it and shows where it misleads.
Standard error with all readings counted.
The standard error is 0.00437 °C. ✅
Interval. The sample is large, so
The naive interval is
Test the assumption. This result assumes 20,160 independent readings. With
Effective sample size.
By this formula the 20,160 readings are worth about 506 independent ones. ✅
Standard error.
The standard error is 6.3 times the naive value. ✅
Interval.
With the effective sample size the interval is
Mean of the daily means. The days are equal in length, so the mean of the 14 daily means is the mean of all readings: 4.0128 °C. ✅
Standard error of the 14-day mean.
The day-to-day scatter gives a standard error of 0.00432 °C. ✅
The t value. There are 14 values, so 13 degrees of freedom and
Interval.
From the daily means the interval is
Put the three in one table.
| Method | Readings counted | 95 percent interval |
|---|---|---|
| Naive, all readings | 20,160 | ± 0.0086 °C |
| Effective sample size | 506 | ± 0.054 °C |
| Daily means, | 14 | ± 0.0093 °C |
The three methods do not agree, and the corrected formula is the one that differs. ✅
Why the formula is too wide here. The formula assumes that the autocorrelation fades steadily: 0.951, then
Why the naive interval is close by accident. The naive rule reasons wrongly, and for this signal two errors nearly cancel: neighbouring readings repeat each other, and readings half a cycle apart oppose each other. A drifting signal has only the first effect, and there the naive interval was right in 24.8 percent of trials. Do not rely on a cancellation you have not checked. ✅
Which to report. The daily means make no assumption about the shape of the signal inside a day. They only need one day to be nearly independent of the next. Report
Check with the script. The Python script below prints 0.0086, 0.0540 and 0.0093 °C for the three intervals, with
The next day, not the mean. The next daily mean of this room is expected within
Split the record. Nothing was changed in the room during the 14 days, so the true difference between the first and the second week is zero. Week 1 has a mean of 4.017 °C (
Interval of a difference. The standard errors of two independent means combine as a square root of the sum of squares.
With scipy.stats.ttest_ind(a, b, equal_var=False) uses) the interval is
What it means. Repeat this split on other quiet periods. If a quiet record often shows a “real” change, the interval is too narrow, usually because the blocks are too short. For the repair in the opening, two 14 day means of
Scatter as a fraction of the mean.
One day differs from the mean by about 27 percent on a typical day. ✅
The target. Three percent of the mean is
Apply the formula.
The formula asks for 309 days, rounding up. ✅
Check by going forward. With 309 days,
Use the first 309 days. Their mean is 596.8 kWh. The mean of the full year is 575.8 kWh. The difference is +3.6 percent, outside the ± 3 percent that the formula promised. ✅
Find the reason: the days are not independent. The lag-1 autocorrelation of daily energy is 0.66, and at a lag of 7 days it is 0.82. Each day resembles the day before and, more strongly, the same day of the week before. The formula counted 309 independent days and they are not. ✅
Find the cause of the dependence. The mean of 30 days starting at day 0 is 557 kWh. Starting at days 90, 180 and 270 it is 733, 577 and 444 kWh. The energy follows the season. Weekdays have a mean of 629.5 kWh and weekend days 440.9 kWh. Most of the 154.7 kWh of scatter is not random noise. It is the weather and the calendar. ✅
Conclusion. A stretch of 309 days in a row leaves out 56 days of one season, so its mean is pulled toward the seasons it contains. To state the yearly mean of this building, use whole years. To state how sure you are of it, the scatter that matters is what remains after weather and weekday are explained. ✅
The script builds data set A and data set B with fixed seeds, so it prints the same numbers on any computer. It calculates the three intervals of Application 1, tests the three methods on 2,000 computer-made drifting signals with a known mean, and calculates the days needed in Application 2. The plot shows the autocorrelation of the cold room readings and the 14 daily means with their interval.
"""How sure is an average? Cold room minutes (data set A) and daily energy (data set B)."""import numpy as npfrom scipy import stats, signalimport matplotlib.pyplot as plt
def cold_room_minutes(seed=11, days=14): rng = np.random.default_rng(seed) n = days * 1440 t = np.empty(n); temp = 4.0; on = False; out = [] for i in range(n): minute = i % 1440 # door openings are more likely in working hours door = (480 <= minute < 1020) and (rng.random() < 0.035) if temp >= 5.0: on = True if temp <= 3.0: on = False temp += (-0.30 if on else 0.10) + (0.35 if door else 0.0) t[i] = temp + rng.normal(0.0, 0.05) # sensor noise, 0.05 °C return t
def building_daily(seed=23, days=730): rng = np.random.default_rng(seed) d = np.arange(days) temp = 21.0 + 4.5 * np.sin(2 * np.pi * (d - 20) / 365.0) + rng.normal(0, 1.6, days) weekday = (d % 7) < 5 # day 0 is a Monday cdd = np.clip(temp - 18.0, 0.0, None) # cooling degree days, base 18 °C energy = 310.0 + 42.0 * cdd + np.where(weekday, 180.0, 0.0) + rng.normal(0, 28.0, days) # an energy-saving measure is installed on day 500: 12 percent less from then on energy[500:] *= 0.88 return d, temp, weekday, energy # kWh a day
def autocorr(x, lag): """Autocorrelation of x at one lag.""" d = x - x.mean() return float((d[:-lag] * d[lag:]).sum() / (d * d).sum())
# ---------- Application 1: mean temperature of the cold room ----------x = cold_room_minutes()n = x.sizemean, s = x.mean(), x.std(ddof=1)print("Cold room, one reading a minute")print(f" n = {n}, mean = {mean:.4f} degC, s = {s:.4f} degC")
se_naive = s / np.sqrt(n)print(f" naive: SE = {se_naive:.5f}, 95 % interval = +/- {1.96 * se_naive:.4f} degC")
r1 = autocorr(x, 1)n_eff = n * (1.0 - r1) / (1.0 + r1)se_eff = s / np.sqrt(n_eff)print(f" r1 = {r1:.4f}, n_eff = {n_eff:.0f}")print(f" with n_eff: SE = {se_eff:.5f}, 95 % interval = +/- {1.96 * se_eff:.4f} degC")print(" autocorrelation at lags 5, 10, 27 min: " + ", ".join(f"{autocorr(x, k):+.3f}" for k in (5, 10, 27)))
daily = x.reshape(14, 1440).mean(axis=1)k = daily.sizes_d = daily.std(ddof=1)t13 = stats.t.ppf(0.975, k - 1)half_d = t13 * s_d / np.sqrt(k)print(" daily means: " + " ".join(f"{v:.3f}" for v in daily))print(f" 14 daily means: mean = {daily.mean():.4f}, s = {s_d:.4f}, " f"SE = {s_d / np.sqrt(k):.5f}, t = {t13:.3f}")print(f" from daily means: 95 % interval = +/- {half_d:.4f} degC " f"({daily.mean() - half_d:.3f} to {daily.mean() + half_d:.3f})")print(f" r1 of the daily means = {autocorr(daily, 1):.2f}")
# ---------- A test of the three methods on a signal with no cycle ----------rng = np.random.default_rng(5)phi, m, trials = 0.95, 5000, 2000 # true mean is 0noise = rng.normal(0.0, 1.0, (trials, m + 500))y = signal.lfilter([1.0], [1.0, -phi], noise, axis=1)[:, 500:]ybar, ys = y.mean(axis=1), y.std(axis=1, ddof=1)dev = y - ybar[:, None]yr1 = (dev[:, :-1] * dev[:, 1:]).sum(axis=1) / (dev * dev).sum(axis=1)half_naive = 1.96 * ys / np.sqrt(m)half_eff = 1.96 * ys / np.sqrt(m * (1.0 - yr1) / (1.0 + yr1))blocks = y.reshape(trials, 20, 250).mean(axis=2)half_block = stats.t.ppf(0.975, 19) * blocks.std(axis=1, ddof=1) / np.sqrt(20)print("Drifting signal (r1 = 0.95, no cycle), 2000 trials: intervals that contain the true mean")for name, half in (("naive", half_naive), ("n_eff", half_eff), ("20 block means", half_block)): print(f" {name:>14}: {100.0 * (np.abs(ybar) < half).mean():.1f} %")
# ---------- Application 2: days needed for a daily energy mean ----------d, temp, weekday, energy = building_daily()e = energy[:365]e_mean, e_s = e.mean(), e.std(ddof=1)print("Building, first 365 days of daily energy")print(f" mean = {e_mean:.1f} kWh, s = {e_s:.1f} kWh, s/mean = {100 * e_s / e_mean:.1f} %")n_need = (1.96 * e_s / (0.03 * e_mean)) ** 2n_days = int(np.ceil(n_need))print(f" days for +/- 3 % at 95 %: {n_need:.1f}, so {n_days} days")print(f" check: 1.96 s / sqrt({n_days}) = {1.96 * e_s / np.sqrt(n_days):.2f} kWh " f"= {100 * 1.96 * e_s / np.sqrt(n_days) / e_mean:.2f} % of the mean")first = e[:n_days].mean()print(f" mean of the first {n_days} days = {first:.1f} kWh, " f"{100 * (first / e_mean - 1):+.1f} % from the year's mean")print(f" r1 of daily energy = {autocorr(e, 1):.2f}, at lag 7 = {autocorr(e, 7):.2f}")print(" 30-day means from days 0, 90, 180, 270: " + ", ".join(f"{e[a:a + 30].mean():.0f}" for a in (0, 90, 180, 270)) + " kWh")wd = weekday[:365]print(f" weekdays: mean {e[wd].mean():.1f}, s {e[wd].std(ddof=1):.1f}; " f"weekend days: mean {e[~wd].mean():.1f}, s {e[~wd].std(ddof=1):.1f} kWh")
# ---------- Plot ----------fig, ax = plt.subplots(2, 1, figsize=(8, 7))lags = np.arange(1, 121)ax[0].plot(lags, [autocorr(x, int(k)) for k in lags], label="cold room readings")ax[0].plot(lags, r1 ** lags, "--", label="what the n_eff formula assumes")ax[0].axhline(0.0, color="gray", linewidth=0.8)ax[0].set_xlabel("lag (minutes)")ax[0].set_ylabel("autocorrelation")ax[0].set_title("Readings one minute apart are not independent")ax[0].legend()ax[1].plot(np.arange(1, 15), daily, "o-", label="daily mean")ax[1].axhspan(daily.mean() - half_d, daily.mean() + half_d, alpha=0.25, label="95 % interval of the 14-day mean")ax[1].axhline(daily.mean(), color="gray", linewidth=0.8)ax[1].set_xlabel("day")ax[1].set_ylabel("mean temperature (degC)")ax[1].set_title("Fourteen daily means and the interval they give")ax[1].legend()fig.tight_layout()fig.savefig("average_uncertainty.png", dpi=120)print("Saved average_uncertainty.png")Expected output
Cold room, one reading a minute n = 20160, mean = 4.0128 degC, s = 0.6203 degC naive: SE = 0.00437, 95 % interval = +/- 0.0086 degC r1 = 0.9510, n_eff = 506 with n_eff: SE = 0.02756, 95 % interval = +/- 0.0540 degC autocorrelation at lags 5, 10, 27 min: +0.289, -0.562, +0.874 daily means: 4.055 4.037 4.015 4.004 3.997 4.000 4.013 3.997 4.006 4.006 4.011 4.007 4.008 4.024 14 daily means: mean = 4.0128, s = 0.0162, SE = 0.00432, t = 2.160 from daily means: 95 % interval = +/- 0.0093 degC (4.003 to 4.022) r1 of the daily means = 0.46Drifting signal (r1 = 0.95, no cycle), 2000 trials: intervals that contain the true mean naive: 24.8 % n_eff: 94.9 % 20 block means: 94.0 %Building, first 365 days of daily energy mean = 575.8 kWh, s = 154.7 kWh, s/mean = 26.9 % days for +/- 3 % at 95 %: 308.1, so 309 days check: 1.96 s / sqrt(309) = 17.25 kWh = 3.00 % of the mean mean of the first 309 days = 596.8 kWh, +3.6 % from the year's mean r1 of daily energy = 0.66, at lag 7 = 0.82 30-day means from days 0, 90, 180, 270: 557, 733, 577, 444 kWh weekdays: mean 629.5, s 130.3; weekend days: mean 440.9, s 126.6 kWhSaved average_uncertainty.pngOn the drifting signal, the effective sample size and the block means contain the true mean close to 95 percent of the time and the naive rule does not. Block means work on both the drifting signal and the cycling cold room, so use them first.
1. A technician measures the air temperature of a store room once a day for 25 days. The mean is 4.20 °C and the standard deviation is 0.60 °C. Find the standard error and the 95 percent confidence interval of the mean. Use
2. Ten daily mean temperatures of a cold room in °C are 4.02, 3.97, 4.05, 4.01, 3.96, 4.04, 3.99, 4.03, 4.00 and 3.98. Find the mean, the standard deviation and the 95 percent confidence interval of the mean. Use
The mean is 4.005 °C and
3. A tank temperature that drifts slowly, with no cycle, is logged once a minute for 7 days (
4. A pumping station uses a mean of 820 kWh a day with a standard deviation of 95 kWh. Its use does not depend on season or weekday. How many days are needed to state the mean within ± 2 percent at 95 percent confidence? How many for ± 5 percent?
For ± 2 percent:
5. Use only the first 7 daily means of Application 1: 4.055, 4.037, 4.015, 4.004, 3.997, 4.000 and 4.013 °C. Find the 95 percent confidence interval of the mean with
The mean is 4.017 °C and
6. Change the script so that it cuts the cold room record into 336 hourly blocks in place of 14 daily blocks. Find the standard deviation of the hourly means, the standard error of the overall mean, and the lag-1 autocorrelation of the hourly means. Explain why the daily blocks are the safer choice.
Use x.reshape(336, 60).mean(axis=1). The hourly means have
A tank temperature drifts slowly. A logger stores 5,000 readings, one a minute, and the software prints a 95 percent interval of the mean using all 5,000 readings. Repeat this on many such records. How often does the printed interval contain the true mean?
Each line is the 95 percent interval of the mean from one record of 5,000 readings (about three and a half days at one a minute) of a room whose true long-run mean is 4.00 °C and whose readings scatter with s = 0.60 °C. A coral line misses the true mean. The same records are kept when you change the rule, so you see the rule, not new luck.
Three questions. Each wrong choice is a mistake people really make, so read the note after you answer.
1. Spot checks on 25 different days give a standard deviation of 0.60 °C and a standard error of 0.12 °C. You want a standard error of 0.06 °C. With the same scatter, how many spot checks, on different days, do you need?
2. The quality file says the cold room mean is 4.013 ± 0.009 °C (95 percent, from 14 daily means). Next morning a reading of 4.6 °C appears. What does this reading tell you?
3. Five weekly mean energies of a pump station have a standard deviation of 40 kWh. What is the half-width of the 95 percent interval of their mean?
No comments yet. Questions, results from your own build, a better way to explain it: all welcome.
Kept on this device only. Nothing is sent anywhere.
Tip: select words in the lesson, or tap a figure or an equation, to put a note right there.
The lesson has changed and these words are no longer in it. Your notes are kept, with the words you chose.