matstat.h

The Matstat library uses single pass algorithms to compute statistic measures such as mean and variance over many values.

The values can be immediately discarded after processing, keeping the memory requirement constant regardless of how many values need to be processed.

The design goal is to provide basic mathematical statistics operations on constrained devices with a “good enough” accuracy to be able to provide some descriptive measures of data. For more accurate measures of statistics, use a fancier library, or copy the data to a PC.

It is important to know that using integer operations will result in lower precision in the computed measures because of truncation.

Matstat library declarations

MATSTAT_STATE_INIT

Empty state initializer.

1
2
3
4
5
6
7
8
(const matstat_state_t) { \
        .sum = 0, \
        .sum_sq = 0, \
        .count = 0, \
        .mean = 0, \
        .min = INT32_MAX, \
        .max = INT32_MIN, \
    }
void matstat_clear(matstat_state_t * state)

Reset state.

Parameters

state:State struct to clear

void matstat_add(matstat_state_t * state, int32_t value)

Add a sample to state.

Parameters

state:State struct to operate on
value:Value to add to the state

int32_t matstat_mean(const matstat_state_t * state)

Return the computed mean value of all samples so far.

Parameters

state:State struct to operate on

Return values

  • arithmetic mean
uint64_t matstat_variance(const matstat_state_t * state)

Compute the sample variance of all samples so far.

Parameters

state:State struct to operate on

Return values

  • sample variance
void matstat_merge(matstat_state_t * dest, const matstat_state_t * src)

Combine two states.

Add the sums and count of src and dest, take the maximum of the max values and minimum of the min values. The result is written to dest.

Parameters

dest:destination state struct
src:source state struct

struct matstat_state_t

Internal state for computing running statistics.

int64_t sum

Sum of values added.

uint64_t sum_sq

Sum of squared differences.

uint32_t count

Number of values added.

int32_t mean

Mean value.

int32_t min

Minimum value seen.

int32_t max

Maximum value seen.