Skip to content

Commit

Permalink
Add median adjustment for even length arrays (#2132)
Browse files Browse the repository at this point in the history
Add median adjustment for even length arrays
  • Loading branch information
shanson7 authored and DanCech committed Nov 28, 2017
1 parent d4eb9cc commit 61ac7f2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
7 changes: 6 additions & 1 deletion webapp/graphite/render/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,12 @@ def safeAvg(values):
def safeMedian(values):
safeValues = [v for v in values if v is not None]
if safeValues:
return sorted(safeValues)[len(safeValues) // 2]
sortedVals = sorted(safeValues)
mid = len(sortedVals) // 2
if len(sortedVals) % 2 == 0:
return float(sortedVals[mid-1] + sortedVals[mid]) / 2
else:
return sortedVals[mid]

def safeStdDev(a):
sm = safeSum(a)
Expand Down
9 changes: 6 additions & 3 deletions webapp/tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,14 +193,17 @@ def test_safeMedian_None(self):
def test_safeMedian_empty_list(self):
self.assertEqual(functions.safeMedian([]), None)

def test_safeMedian_all_numbers(self):
self.assertEqual(functions.safeMedian([1,2,3,4]), 3)
def test_safeMedian_all_numbers_odd_len(self):
self.assertEqual(functions.safeMedian([1,2,3,4,5]), 3)

def test_safeMedian_all_numbers_even_len(self):
self.assertAlmostEqual(functions.safeMedian([1,2,3,4]), 2.5)

def test_safeMedian_all_None(self):
self.assertEqual(functions.safeMedian([None,None,None,None]), None)

def test_safeMedian_mixed(self):
self.assertEqual(functions.safeMedian([10,None,5,None]), 10)
self.assertAlmostEqual(functions.safeMedian([10,None,5,None]), 7.5)

#
# Test safeStdDev()
Expand Down

0 comments on commit 61ac7f2

Please sign in to comment.