From f2b7e719543408650fef7e3290f77962654453a9 Mon Sep 17 00:00:00 2001 From: Will Hawkins Date: Fri, 14 Jul 2023 10:59:05 -0400 Subject: [Bugfix]: Out of range percentile calculations It was possible for a user of percentile-calculation functions to request a percentile that caused the underlying array of values to be accessed out of bounds. This patch fixes that error. Signed-off-by: Will Hawkins --- utilities/math.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'utilities') diff --git a/utilities/math.go b/utilities/math.go index 1ecca61..96b9f10 100644 --- a/utilities/math.go +++ b/utilities/math.go @@ -36,15 +36,18 @@ func CalculateAverage[T Number](elements []T) float64 { func CalculatePercentile[T Number]( elements []T, - p int, + p uint, ) (result T) { result = T(0) - if p < 0 || p > 100 { + if p < 1 || p > 100 { return } sort.Slice(elements, func(l int, r int) bool { return elements[l] < elements[r] }) - pindex := int64((float64(p) / float64(100)) * float64(len(elements))) + pindex := int((float64(p) / float64(100)) * float64(len(elements))) + if pindex >= len(elements) { + return + } result = elements[pindex] return } -- cgit v1.2.3