summaryrefslogtreecommitdiff
path: root/utilities/math.go
diff options
context:
space:
mode:
authorWill Hawkins <[email protected]>2023-07-14 10:59:05 -0400
committerWill Hawkins <[email protected]>2023-07-14 10:59:05 -0400
commitf2b7e719543408650fef7e3290f77962654453a9 (patch)
tree6b9ad557712d19a2362c0055908a8c25b58cafbe /utilities/math.go
parentdf37c3e0d572ff3b4b4de3e9919402e8e0ccf971 (diff)
[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 <[email protected]>
Diffstat (limited to 'utilities/math.go')
-rw-r--r--utilities/math.go9
1 files changed, 6 insertions, 3 deletions
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
}