fix: propagate error from Quartile for inputs too small for quartiles

Quartile computed the median of empty slices for inputs with fewer than
three elements and discarded the resulting error, returning NaN quartiles
with a nil error. The silent NaN then leaked into InterQuartileRange,
Midhinge and Trimean. Propagate the error instead, mirroring the existing
EmptyInputErr handling.
This commit is contained in:
dualfroz committed 2026-09-04 02:56:39 +02:00
1 parent bc246e8d16
commit 4bf1fbf3b8
2 files changed
+56 -7

No files matched your search

+28
View File
@@ -41,6 +41,19 @@ func TestQuartile(t *testing.T) {
}
}
func TestQuartileSingleElement(t *testing.T) {
// A single element has no lower or upper half, so it cannot have
// quartiles. Quartile must return an error instead of silently
// producing NaN values with a nil error.
quartiles, err := stats.Quartile([]float64{1})
if err == nil {
t.Errorf("Single element slice should have returned an error")
}
if quartiles != (stats.Quartiles{}) {
t.Errorf("Errored result should be the zero Quartiles value, got %+v", quartiles)
}
}
func TestInterQuartileRange(t *testing.T) {
s1 := []float64{102, 104, 105, 107, 108, 109, 110, 112, 115, 116, 118}
iqr, _ := stats.InterQuartileRange(s1)
@@ -53,6 +66,11 @@ func TestInterQuartileRange(t *testing.T) {
if err == nil {
t.Errorf("Empty slice should have returned an error")
}
_, err = stats.InterQuartileRange([]float64{1})
if err == nil {
t.Errorf("Single element slice should have returned an error")
}
}
func TestMidhinge(t *testing.T) {
@@ -67,6 +85,11 @@ func TestMidhinge(t *testing.T) {
if err == nil {
t.Errorf("Empty slice should have returned an error")
}
_, err = stats.Midhinge([]float64{1})
if err == nil {
t.Errorf("Single element slice should have returned an error")
}
}
func TestTrimean(t *testing.T) {
@@ -81,4 +104,9 @@ func TestTrimean(t *testing.T) {
if err == nil {
t.Errorf("Empty slice should have returned an error")
}
_, err = stats.Trimean([]float64{1})
if err == nil {
t.Errorf("Single element slice should have returned an error")
}
}