Skip to content

Commit ca6f1bc

Browse files
committed
Fix bug of zero KDE bandwidth
1 parent 21d5353 commit ca6f1bc

File tree

1 file changed

+13
-1
lines changed
  • src/stats/univariate/kde

1 file changed

+13
-1
lines changed

src/stats/univariate/kde/mod.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,19 @@ impl Bandwidth {
8484
let n = A::cast(sample.len());
8585
let sigma = sample.std_dev(None);
8686

87-
sigma * (factor / n).powf(exponent)
87+
// When all samples have the same value (rare case, but not impossible),
88+
// the standard deviation will be zero, and the Silverman
89+
// method will produce a zeroed bandwidth.
90+
// But the bandwidth should always be a positive (non-zero) number,
91+
// so if that happens, the optimal bandwidth should be very small,
92+
// as this will create a very sharp peak at the single data point,
93+
// accurately reflecting the fact that all data is concentrated
94+
// at that single value.
95+
if sigma.is_zero() {
96+
A::cast(0.001)
97+
} else {
98+
sigma * (factor / n).powf(exponent)
99+
}
88100
}
89101
}
90102
}

0 commit comments

Comments
 (0)