The core idea: Welford's online algorithm
The standard way to compute mean and standard deviation requires storing all samples first, then doing two passes. That's fine in Python. On a microcontroller with 320 KB of RAM, it's a non-starter.
John Welford solved this in 1962. His algorithm maintains a running mean and variance in a single pass, using only three values:
typedef struct { uint32_t count ; // samples processed float mean ; // running mean float M2 ; // sum of squared deviations from mean float threshold_sigma ; // alert threshold (e.g. 3.0 = 3σ) uint32_t min_samples ; // warm-up period before detection starts uint32_t window_size ; // 0 = infinite, N = sliding window } ArdentZScore ; // sizeof == 24 bytes
Enter fullscreen mode
Exit fullscreen mode
The update step is four lines:
bool ard_zscore_update ( ArdentZScore * ctx , float sample ) { ctx -> count ++ ; float delta = sample - ctx -> mean ; ctx -> mean += delta / ctx -> count ; float delta2 = sample - ctx -> mean ; ctx -> M2 += delta *…