diff --git a/webapp/graphite/render/functions.py b/webapp/graphite/render/functions.py index 4581e9b0d..3cfb9115e 100644 --- a/webapp/graphite/render/functions.py +++ b/webapp/graphite/render/functions.py @@ -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) diff --git a/webapp/tests/test_functions.py b/webapp/tests/test_functions.py index 41224bc2d..0ba9807db 100644 --- a/webapp/tests/test_functions.py +++ b/webapp/tests/test_functions.py @@ -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()