Simvik

Compensated summation

Add up many float samples without the total drifting. A medium embedded C problem (Floating point on the Cortex-M33), run and graded in the browser.

medium · Floating point on the Cortex-M33 · float · fpu

A logger on a Pico 2 adds the energy of every sample to a float total. Each addition rounds to 24 bits of mantissa, and once the total is large every small sample loses most of its bits: 100 000 additions of 0.1 come out near 9998.6, not 10 000.

Return the sum of the n values in x using Kahan's compensated summation: keep a second float, c, with the part of each addition that was rounded away, and take it off the next value before it is added. Work in float only (no double).

Starter code

float sum_floats(const float *x, int n) {
  float total = 0.0f;
  for (int i = 0; i < n; i++) total += x[i];
  return total;
}

Example tests

A few values

float x[4] = { 1.5f, 2.25f, -0.75f, 4.0f };
printf("%.2f\n", sum_floats(x, 4));

Expected output:

7.00

Many small values

static float x[10000];
for (int i = 0; i < 10000; i++) x[i] = 0.1f;
printf("%.2f\n", sum_floats(x, 10000));

Expected output:

1000.00

Learn it first

More Floating point on the Cortex-M33 problems