commit 17725ded63f3bb869670747b45ed00b3c0ec08f3
parent 5bde959937eaf8935c9a775544a26db3282b4272
Author: Eduardo Fontana Lazzari <edufonlaz@gmail.com>
Date: Mon, 6 Apr 2026 13:15:41 +0200
Clamp variance to avoid negative values
In zero (or near-zero) variance cases, floating-point rounding errors
can produce small negative variance values. Clamp the result to 0 to
prevent propagating invalid values to the standard error computation,
specially considering it depends on the square root of the variance.
Diffstat:
1 file changed, 3 insertions(+), 0 deletions(-)
diff --git a/src/sphor_accum.c b/src/sphor_accum.c
@@ -147,6 +147,9 @@ accum_compute_estim
/* Compute the sample variance. This formula is equivalent to
* var = 1 / (n-1) sum(x_i - <x>)^2 */
var = (sum2 - sum * sum / samples) / (samples - 1);
+ /* Clamp variance to 0 to guard against small negative values
+ * caused by floating-point rounding errors */
+ var = var < 0 ? 0 : var;
std_err = sqrt (var / samples);
estim->mean = mean;