From 3477f09555a06d084c8165f179fbf6a021ea6f90 Mon Sep 17 00:00:00 2001 From: Ben Morgan Date: Wed, 24 Aug 2016 09:41:42 +0200 Subject: [PATCH] Make it harder for Mean() and StdDev() to overflow --- hdr.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/hdr.go b/hdr.go index 02540dd..bceb9e1 100644 --- a/hdr.go +++ b/hdr.go @@ -155,14 +155,15 @@ func (h *Histogram) Mean() float64 { if h.totalCount == 0 { return 0 } - var total int64 + var mean float64 + totalCount := float64(h.totalCount) i := h.iterator() for i.next() { if i.countAtIdx != 0 { - total += i.countAtIdx * h.medianEquivalentValue(i.valueFromIdx) + mean += float64(i.countAtIdx*h.medianEquivalentValue(i.valueFromIdx)) / totalCount } } - return float64(total) / float64(h.totalCount) + return mean } // StdDev returns the approximate standard deviation of the recorded values. @@ -173,16 +174,17 @@ func (h *Histogram) StdDev() float64 { mean := h.Mean() geometricDevTotal := 0.0 + totalCount := float64(h.totalCount) i := h.iterator() for i.next() { if i.countAtIdx != 0 { dev := float64(h.medianEquivalentValue(i.valueFromIdx)) - mean - geometricDevTotal += (dev * dev) * float64(i.countAtIdx) + geometricDevTotal += (dev * dev) * float64(i.countAtIdx) / totalCount } } - return math.Sqrt(geometricDevTotal / float64(h.totalCount)) + return math.Sqrt(geometricDevTotal) } // Reset deletes all recorded values and restores the histogram to its original