BeginnerLesson 8 of 205 min read

Project: Weather Statistics With Mean, Median and Standard Deviation

Build a program that computes mean, median, minimum, maximum, standard deviation and a moving average from readings, prints a tidy table and is verified against Python's statistics module.

In this lesson you will

  • Combine vectors, functions and algorithms
  • Compute descriptive statistics
  • Format a table with std::format
  • Verify against an independent library

About 28 minutes

Numbers from the roof, summarised

This project joins the first seven lessons. Elena has thirteen readings and wants the usual summary: the mean, the median, the smallest and largest value, the standard deviation, and a moving average that smooths the sequence. You will write small functions, each doing one thing, use standard algorithms, format a table, and then prove the numbers right with a completely separate implementation. Writing the formulas down before coding keeps the program honest.

Statistic Formula
Mean Sum of the values divided by the count
Median The middle value of the sorted list, or the average of the two middle values
Sample standard deviation Square root of the sum of squared differences from the mean, divided by n – 1
Moving average of width 3 The mean of each window of 3 consecutive values

The sample standard deviation divides by n – 1 and not by n. This is called Bessel’s correction, and it is the right choice when the readings are a sample of a larger process, as here. Using n would give the population standard deviation, and the two are close but not equal. The program passes the vector by const reference, so that no copy is made, and copies it only inside the median function, which needs a sorted version.

#include <algorithm>
#include <cmath>
#include <format>
#include <iostream>
#include <numeric>
#include <vector>

double mean(const std::vector<double>& v) { return std::accumulate(v.begin(), v.end(), 0.0) / v.size(); }
double median(std::vector<double> v) {
    std::sort(v.begin(), v.end());
    std::size_t n = v.size();
    return n % 2 ? v[n / 2] : (v[n / 2 - 1] + v[n / 2]) / 2;
}
double stddev(const std::vector<double>& v) {
    double m = mean(v), s = 0;
    for (double x : v) s += (x - m) * (x - m);
    return std::sqrt(s / (v.size() - 1));
}
std::vector<double> moving_average(const std::vector<double>& v, std::size_t w) {
    std::vector<double> out;
    for (std::size_t i = 0; i + w <= v.size(); ++i)
        out.push_back(std::accumulate(v.begin() + i, v.begin() + i + w, 0.0) / w);
    return out;
}

int main() {
    std::vector<double> t{21.5, 19.0, 23.4, 18.2, 25.1, 22.0, 20.3, 24.8, 17.9, 26.2, 23.1, 19.9, 22.6};
    auto [mn, mx] = std::minmax_element(t.begin(), t.end());
    std::cout << std::format("{:<10}{:>10}\n", "statistic", "value");
    std::cout << std::format("{:<10}{:>10}\n", "count", t.size());
    std::cout << std::format("{:<10}{:>10.4f}\n", "mean", mean(t));
    std::cout << std::format("{:<10}{:>10.4f}\n", "median", median(t));
    std::cout << std::format("{:<10}{:>10.4f}\n", "min", *mn);
    std::cout << std::format("{:<10}{:>10.4f}\n", "max", *mx);
    std::cout << std::format("{:<10}{:>10.4f}\n", "stddev", stddev(t));
    auto ma = moving_average(t, 3);
    std::cout << "moving average (3): " << ma.size() << " values, first " << std::format("{:.4f}", ma.front()) << ", last " << std::format("{:.4f}", ma.back()) << "\n";
}
statistic      value
count             13
mean         21.8462
median       22.0000
min          17.9000
max          26.2000
stddev        2.6788
moving average (3): 11 values, first 21.3000, last 21.8667

The table reports 13 readings with a mean of 21.8462, a median of 22.0000, a range from 17.9 to 26.2 and a sample standard deviation of 2.6788. The moving average with a window of 3 has 11 values, which is the number of readings minus 2, the first is 21.3000 and the last 21.8667. Each function does one job, takes its input by const reference, and the median function takes a copy by value on purpose, since sorting would otherwise change the caller’s data.

To verify the numbers, the course computed the same statistics with Python’s statistics module, which is a completely independent implementation. It gave a mean of 21.8462, a median of 22.0000 and a sample standard deviation of 2.6788, and the same first and last moving averages, 21.3000 and 21.8667. All of them agree with the C++ results to four decimals. Notice that the C++ program used n – 1, the same convention as statistics.stdev, and that the population standard deviation would have been 2.5737, a different number, which is a reminder that you must check the convention before comparing statistics.

Check by hand: the thirteen readings add up to 284.0, and 284.0 divided by 13 is 21.8462. With thirteen values the median is the seventh in sorted order, 22.0.

Check which standard deviation you mean

Dividing by n gives the population value and dividing by n – 1 gives the sample value. Libraries differ, so read the documentation before you compare results.

Verify with another tool

A spreadsheet or Python gives you a second opinion in a minute. If the two disagree, find out why before trusting either.

About this course

Every program in this lesson was compiled with GCC 13 using -std=c++20 -Wall -Wextra and run while the course was written. C++ has a new standard every three years and compilers differ in what they support, so check your compiler’s documentation and cppreference.com for the current state.

Practice

Add the mode of rounded readings, and the longest run of readings above the mean. Add a function that removes outliers more than two standard deviations from the mean, and check the result by hand on a short list.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Why does the median function take its vector by value?

  1. It sorts a copy and leaves the caller’s data alone
  2. To be faster
  3. Because it is a rule
  4. To allow null

Sorting changes the order.

What does n – 1 in the standard deviation formula do?

  1. Gives the population value
  2. Removes outliers
  3. Sorts the data
  4. Gives the sample standard deviation

Bessel’s correction.

How many values has a moving average of width 3 over 13 readings?

  1. 13
  2. 10
  3. 3
  4. 11

n – w + 1.

How was the program verified?

  1. By trusting it
  2. By running it twice
  3. Against Python’s statistics module
  4. By its output length

All numbers agreed.

Why pass the vector by const reference?

  1. To change it
  2. To sort it
  3. To avoid copying while promising not to change it
  4. To print it

Lesson 5.

Summary

  • A project combines functions, vectors and algorithms.
  • Mean, median and sample standard deviation have simple formulas.
  • Check conventions such as n – 1.
  • Verify with an independent implementation.

Next lesson

Lesson 9 covers pointers and memory, with a real leak report.

Questions

Why is the median useful?

It is not affected much by extreme values, unlike the mean.

Can I do this with the standard library only?

Yes, as here. For larger numerical work, libraries such as Eigen help, and for statistics many people use Python or R.

What does std::format do with a size_t?

It prints it as an integer, as the count line shows.

Progress is saved in this browser.