Skip to content

Commit

Permalink
lib: fix calculation of std and cv
Browse files Browse the repository at this point in the history
  • Loading branch information
RafaelGSS committed Sep 18, 2024
1 parent f9449eb commit 157b675
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions lib/histogram.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,14 @@ class StatisticalHistogram {
}

calculateStd() {
const avgSquares = this.all.reduce(
(acc, value) => Math.min(Number.MAX_SAFE_INTEGER, Math.pow(value, 2) + acc), 0,
) * (1 / this.all.length);

this.stddev = Math.sqrt(Math.max(0, this.all.length / (this.all.length - 1) * (avgSquares - (this.mean * this.mean))));
if (this.all.length < 2) {
this.stddev = 0;
return;
}
const variance = this.all.reduce((acc, value) => {
return acc + Math.pow(value - this.mean, 2);
}, 0) / (this.all.length - 1);
this.stddev = Math.sqrt(variance);
}

/**
Expand All @@ -125,7 +128,7 @@ class StatisticalHistogram {
* - https://github.com/google/benchmark/blob/159eb2d0ffb85b86e00ec1f983d72e72009ec387/src/statistics.ccL81-L88
*/
calculateCv() {
if (this.all.length < 2) {
if (this.all.length < 2 || this.mean === 0) {
this.cv = 0;
return;
}
Expand Down

0 comments on commit 157b675

Please sign in to comment.