From 88db8a29d097ddf258f12ff0ca523c18b8a784ec Mon Sep 17 00:00:00 2001 From: TimLai666 <43640816+TimLai666@users.noreply.github.com> Date: Sat, 14 Sep 2024 16:55:13 +0800 Subject: [PATCH] =?UTF-8?q?Mode=E5=9B=9E=E5=82=B3=E6=94=B9float64?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- datalist.go | 30 +++++++++++++++++++----------- insyra_test.go | 10 ++++++++++ 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/datalist.go b/datalist.go index fed4abc..b8404ea 100644 --- a/datalist.go +++ b/datalist.go @@ -79,7 +79,7 @@ type IDataList interface { WeightedMean(weights interface{}) float64 GMean() float64 Median() float64 - Mode() interface{} + Mode() float64 MAD() interface{} Stdev() interface{} StdevP() interface{} @@ -1311,21 +1311,29 @@ func (dl *DataList) Median() float64 { } // Mode calculates the mode of the DataList. -// Returns the mode. -// Returns nil if the DataList is empty. -// Mode returns the mode of the DataList. -func (dl *DataList) Mode() interface{} { +// Returns math.NaN() if the DataList is empty or if no valid elements can be used. +func (dl *DataList) Mode() float64 { if len(dl.data) == 0 { - LogWarning("DataList.Mode(): DataList is empty, returning nil.") - return nil + LogWarning("DataList.Mode(): DataList is empty.") + return math.NaN() } - freqMap := make(map[interface{}]int) + freqMap := make(map[float64]int) for _, v := range dl.data { - freqMap[v]++ + vfloat, ok := ToFloat64Safe(v) + if !ok { + LogWarning("DataList.Mode(): Element %v is not a numeric type, skipping.", v) + continue + } + freqMap[vfloat]++ + } + + if len(freqMap) == 0 { + LogWarning("DataList.Mode(): No valid elements to compute mode.") + return math.NaN() } - var mode interface{} + var mode float64 maxFreq := 0 for k, v := range freqMap { if v > maxFreq { @@ -1334,7 +1342,7 @@ func (dl *DataList) Mode() interface{} { } } - return mode.(float64) + return mode } // MAD calculates the mean absolute deviation of the DataList. diff --git a/insyra_test.go b/insyra_test.go index c6d74eb..3efb8b0 100644 --- a/insyra_test.go +++ b/insyra_test.go @@ -208,6 +208,16 @@ func TestMedian(t *testing.T) { } } +// 測試 Mode 函數 +func TestMode(t *testing.T) { + dl := NewDataList(1, 2, 3, 2, 4) + mode := dl.Mode() + + if !float64Equal(mode, 2) { + t.Errorf("Expected mode 2, got %v", mode) + } +} + // 測試 Stdev 函數 func TestStdev(t *testing.T) { dl := NewDataList(1, 2, 3, 4)