Skip to content

Commit

Permalink
Mode回傳改float64
Browse files Browse the repository at this point in the history
  • Loading branch information
TimLai666 committed Sep 14, 2024
1 parent 48e50a5 commit 88db8a2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
30 changes: 19 additions & 11 deletions datalist.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down Expand Up @@ -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 {
Expand All @@ -1334,7 +1342,7 @@ func (dl *DataList) Mode() interface{} {
}
}

return mode.(float64)
return mode
}

// MAD calculates the mean absolute deviation of the DataList.
Expand Down
10 changes: 10 additions & 0 deletions insyra_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 88db8a2

Please sign in to comment.