Skip to content

Commit

Permalink
淘汰Median的高精度模式
Browse files Browse the repository at this point in the history
  • Loading branch information
TimLai666 committed Sep 14, 2024
1 parent 741de66 commit d732e3b
Showing 1 changed file with 4 additions and 29 deletions.
33 changes: 4 additions & 29 deletions datalist.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ type IDataList interface {
Mean() float64
WeightedMean(weights interface{}) float64
GMean() float64
Median(highPrecision ...bool) interface{}
Median() interface{}
Mode() interface{}
MAD() interface{}
Stdev(highPrecision ...bool) interface{}
Expand Down Expand Up @@ -1273,55 +1273,30 @@ func (dl *DataList) GMean() float64 {
// Median calculates the median of the DataList.
// Returns the median.
// Returns nil if the DataList is empty.
// Turn on highPrecision to return a big.Rat instead of a float64.
func (dl *DataList) Median(highPrecision ...bool) interface{} {
func (dl *DataList) Median() interface{} {
if len(dl.data) == 0 {
LogWarning("DataList.Median(): DataList is empty, returning nil.")
return nil
}

// 檢查參數數量
if len(highPrecision) > 1 {
LogWarning("DataList.Median(): Too many arguments, returning nil.")
return nil
}

// 對數據進行排序
sortedData := make([]float64, len(dl.data))
copy(sortedData, dl.ToF64Slice())
sliceutil.Sort(sortedData)

mid := len(sortedData) / 2
useHighPrecision := len(highPrecision) == 1 && highPrecision[0]

if len(sortedData)%2 == 0 {
// 當元素個數為偶數時,返回中間兩個數的平均值
mid1 := ToFloat64(sortedData[mid-1])
mid2 := ToFloat64(sortedData[mid])

if useHighPrecision {
// 使用 big.Rat 進行精確的有理數運算
ratMid1 := new(big.Rat).SetFloat64(mid1)
ratMid2 := new(big.Rat).SetFloat64(mid2)

// 計算平均值
sum := new(big.Rat).Add(ratMid1, ratMid2)
mean := new(big.Rat).Quo(sum, big.NewRat(2, 1))

// 返回高精度結果
return mean
} else {
// 使用 float64 計算並返回
return (mid1 + mid2) / 2
}
// 使用 float64 計算並返回
return (mid1 + mid2) / 2
}

// 當元素個數為奇數時,返回中間的那個數
midValue := ToFloat64(sortedData[mid])
if useHighPrecision {
return new(big.Rat).SetFloat64(midValue)
}

return midValue
}

Expand Down

0 comments on commit d732e3b

Please sign in to comment.