fix: return the value as all three quartiles for single-element input
Quartile called Median on empty half-slices when the input held one value
and discarded both errors, so it returned {NaN, v, NaN} with a nil error.
The NaN spread silently through InterQuartileRange, Midhinge and Trimean.
A single observation is its own lower hinge, median and upper hinge, which
is what Percentile already returns for the same data. Return that instead,
and note why the remaining discarded Median errors cannot fire.
This commit is contained in:
1 parent
05657cd5a8
commit
62beb61195
3 files changed
+57
-1
No files matched your search
+13
-1
@@ -10,6 +10,9 @@ type Quartiles struct {
|
||||
}
|
||||
|
||||
// Quartile returns the three quartile points from a slice of data
|
||||
//
|
||||
// A single value is its own lower hinge, median and upper hinge, so all
|
||||
// three quartiles are that value.
|
||||
func Quartile(input Float64Data) (Quartiles, error) {
|
||||
|
||||
il := input.Len()
|
||||
@@ -17,6 +20,14 @@ func Quartile(input Float64Data) (Quartiles, error) {
|
||||
return Quartiles{}, EmptyInputErr
|
||||
}
|
||||
|
||||
// One value is its own quartiles, which also matches what Percentile
|
||||
// returns for that value at any percent. The general path below cannot
|
||||
// produce it: the cutoffs would leave both halves empty and the two
|
||||
// hinges would come back as NaN.
|
||||
if il == 1 {
|
||||
return Quartiles{input[0], input[0], input[0]}, nil
|
||||
}
|
||||
|
||||
// Start by sorting a copy of the slice
|
||||
copy := sortedCopy(input)
|
||||
|
||||
@@ -32,7 +43,8 @@ func Quartile(input Float64Data) (Quartiles, error) {
|
||||
c2 = c1 + 1
|
||||
}
|
||||
|
||||
// Find the Medians with the cutoff points
|
||||
// Find the Medians with the cutoff points. Both halves hold at least
|
||||
// one value for every length above one, so Median cannot fail here.
|
||||
Q1, _ := Median(copy[:c1])
|
||||
Q2, _ := Median(copy)
|
||||
Q3, _ := Median(copy[c2:])
|
||||
|
||||
Reference in new issue
Block a user