Skip to content

Commit cb378c8

Browse files
committed
[hist] Improve stability of ComputeVariance()
1 parent cac73c3 commit cb378c8

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

hist/histv7/inc/ROOT/RHistStats.hxx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ public:
132132
/// \f]
133133
/// With some rewriting, this is equivalent to:
134134
/// \f[
135-
/// \sigma^2 = \frac{\sum w_i \cdot x_i^2}{\sum w_i} - \frac{(\sum w_i \cdot x_i)^2}{(\sum w_i)^2}
135+
/// \sigma^2 = \frac{\sum w_i \cdot x_i^2}{\sum w_i} - \mu^2
136136
/// \f]
137137
///
138138
/// This function does not include Bessel's correction needed for an unbiased estimator of population variance.
@@ -147,7 +147,8 @@ public:
147147
if (fSumW == 0) {
148148
return 0;
149149
}
150-
return (stats.fSumWX2 - stats.fSumWX * stats.fSumWX / fSumW) / fSumW;
150+
double mean = ComputeMean(dim);
151+
return stats.fSumWX2 / fSumW - mean * mean;
151152
}
152153

153154
/// Compute the standard deviation of unbinned values.

hist/histv7/test/hist_stats.cxx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,16 @@ TEST(RHistStats, ComputeKurtosisWeighted)
342342
EXPECT_FLOAT_EQ(stats.ComputeKurtosis(2), -1.2483086);
343343
}
344344

345+
TEST(RHistStats, ComputeSkewnessKurtosisVar0)
346+
{
347+
RHistStats stats(1);
348+
stats.Fill(1, RWeight(0.1));
349+
ASSERT_EQ(stats.GetNEntries(), 1);
350+
EXPECT_EQ(stats.ComputeVariance(), 0);
351+
EXPECT_EQ(stats.ComputeSkewness(), 0);
352+
EXPECT_EQ(stats.ComputeKurtosis(), 0);
353+
}
354+
345355
TEST(RHistStats, FillInvalidNumberOfArguments)
346356
{
347357
RHistStats stats1(1);

0 commit comments

Comments
 (0)