go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/mathutil/percentile.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package mathutil 9 10 import "math" 11 12 // Percentile finds the relative standing in a slice of floats. 13 // `percent` should be given on the interval [0,100.0). 14 func Percentile[T Operatable](input []T, percent float64) (output T) { 15 if len(input) == 0 { 16 return 17 } 18 output = PercentileSorted(CopySort(input), percent) 19 return 20 } 21 22 // PercentileSorted finds the relative standing in a sorted slice of floats. 23 // `percent` should be given on the interval [0,100.0). 24 func PercentileSorted[T Operatable](sortedInput []T, percent float64) (percentile T) { 25 if len(sortedInput) == 0 { 26 return 27 } 28 index := (percent / 100.0) * float64(len(sortedInput)) 29 i := int(math.RoundToEven(index)) 30 if index == float64(int64(index)) { 31 percentile = (sortedInput[i-1] + sortedInput[i]) / 2.0 32 } else { 33 percentile = sortedInput[i-1] 34 } 35 return percentile 36 }