CKTIS / C
reductions and statistics — concept C23
A reduction folds a sequence into one value; sums and statistics must handle empty input, choose an accumulator that avoids overflow, and account for floating-point rounding error.
Version: C23
Syntax
reductions and statisticsA reduction folds a sequence into one value; sums and statistics must handle empty input, choose an accumulator that avoids overflow, and account for floating-point rounding error.
For an integer sum, choose a wider accumulator and check overflow before addition; for a mean, return a separate error when count == 0. For floating point, Kahan summation or pairwise summation can reduce order-dependent error.
Test empty input, one element, values of very different magnitude, NaN, and infinity. sum / count performs integer division when both operands are integers; variance computed as a difference of large values can lose precision and needs a more stable algorithm.
A prefix sum (inclusive scan) stores at position i the sum of elements 0..i. exclusive prefix offsets store the sum of elements before i, so the first offset is the identity 0 and a separate final total gives the complete size; this is useful for assigning disjoint ranges. Check accumulator overflow before addition. A parallel scan requires an associative operation; floating-point addition is not strictly associative, so changing the reduction tree can change low-order bits.
Examples
#include <stdio.h>
int main(void) { double values[] = {2.0, 4.0, 6.0}; double sum = 0; for (size_t i = 0; i < 3; ++i) sum += values[i]; printf("%.1f\n", sum / 3); return 0; }
Result
4.0
A reduction folds a sequence into one value; sums and statistics must handle empty input, choose an accumulator that avoids overflow, and account for floating-point rounding error.