From 018c11591af1d9a04bd26d4c6b9d58b064f018d4 Mon Sep 17 00:00:00 2001 From: TimLai666 <43640816+TimLai666@users.noreply.github.com> Date: Sat, 14 Sep 2024 15:12:37 +0800 Subject: [PATCH] =?UTF-8?q?Max=E5=9B=9E=E5=82=B3=E5=80=BC=E6=94=B9float64?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- datalist.go | 38 +++++++++++++++++++++----------------- insyra_test.go | 2 +- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/datalist.go b/datalist.go index 02a2e85..c2148b8 100644 --- a/datalist.go +++ b/datalist.go @@ -73,7 +73,7 @@ type IDataList interface { Capitalize() *DataList // Statistics Sum() float64 - Max() interface{} + Max() float64 Min() interface{} Mean() float64 WeightedMean(weights interface{}) interface{} @@ -727,14 +727,14 @@ func (dl *DataList) Normalize() *DataList { go dl.updateTimestamp() }() min, max := dl.Min(), dl.Max() - if min == nil || max == nil { + if min == nil || math.IsNaN(max) { LogWarning("Normalize: Cannot normalize due to invalid Min/Max values.") return nil } for i, v := range dl.Data() { vfloat := conv.ParseF64(v) - dl.data[i] = (vfloat - min.(float64)) / (max.(float64) - min.(float64)) + dl.data[i] = (vfloat - min.(float64)) / (max - min.(float64)) } return dl } @@ -1086,26 +1086,25 @@ func (dl *DataList) Sum() float64 { } // Max returns the maximum value in the DataList. -// Returns the maximum value. -// Returns nil if the DataList is empty. -// Max returns the maximum value in the DataList, or nil if the data types cannot be compared. -func (dl *DataList) Max() interface{} { - defer func() { - r := recover() - if r != nil { - LogWarning("DataList.Max(): Data types cannot be compared, returning nil.") - } - }() +// Returns math.NaN() if the DataList is empty or if no elements can be converted to float64. +func (dl *DataList) Max() float64 { if len(dl.data) == 0 { - return nil + LogWarning("DataList.Max(): DataList is empty.") + return math.NaN() } - var max = math.NaN() + var max float64 + var foundValid bool for _, v := range dl.data { - vfloat := conv.ParseF64(v) - if math.IsNaN(max) { + vfloat, ok := ToFloat64Safe(v) + if !ok { + LogWarning("DataList.Max(): Element %v is not a numeric type, skipping.", v) + continue + } + if !foundValid { max = vfloat + foundValid = true continue } if vfloat > max { @@ -1113,6 +1112,11 @@ func (dl *DataList) Max() interface{} { } } + if !foundValid { + LogWarning("DataList.Max(): No valid elements to compute maximum.") + return math.NaN() + } + return max } diff --git a/insyra_test.go b/insyra_test.go index 0518762..b263bca 100644 --- a/insyra_test.go +++ b/insyra_test.go @@ -142,7 +142,7 @@ func TestMax(t *testing.T) { dl := NewDataList(1, 2, 3, 4) max := dl.Max() - if v, ok := max.(float64); !ok || !float64Equal(v, 4) { + if !float64Equal(max, 4) { t.Errorf("Expected max 4, got %v", max) } }