github.com/blend/go-sdk@v1.20220411.3/mathutil/median.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package mathutil 9 10 // Median gets the median number in a slice of numbers 11 func Median(input []float64) (median float64) { 12 l := len(input) 13 if l == 0 { 14 return 0 15 } 16 17 median = MedianSorted(CopySort(input)) 18 return 19 } 20 21 // MedianSorted gets the median number in a sorted slice of numbers 22 func MedianSorted(sortedInput []float64) (median float64) { 23 l := len(sortedInput) 24 if l == 0 { 25 return 0 26 } 27 28 if l%2 == 0 { 29 median = (sortedInput[(l>>1)-1] + sortedInput[l>>1]) / 2.0 30 } else { 31 median = sortedInput[l>>1] 32 } 33 34 return median 35 }