From 3a687b33d4c295050b42e688099b34b857e02b94 Mon Sep 17 00:00:00 2001 From: Brendan Tracey Date: Fri, 29 Sep 2017 22:27:21 -0600 Subject: [PATCH] stat: Improve documentation and test for Moment (#248) --- stat/stat.go | 6 ++++-- stat/stat_test.go | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/stat/stat.go b/stat/stat.go index 8696e91c..c7ca64f1 100644 --- a/stat/stat.go +++ b/stat/stat.go @@ -903,6 +903,7 @@ func BivariateMoment(r, s float64, x, y, weights []float64) float64 { // If weights is nil then all of the weights are 1. If weights is not nil, then // len(x) must equal len(weights). func Moment(moment float64, x, weights []float64) float64 { + // This also checks that x and weights have the same length. mean := Mean(x, weights) if weights == nil { var m float64 @@ -916,8 +917,9 @@ func Moment(moment float64, x, weights []float64) float64 { sumWeights float64 ) for i, v := range x { - m += weights[i] * math.Pow(v-mean, moment) - sumWeights += weights[i] + w := weights[i] + m += w * math.Pow(v-mean, moment) + sumWeights += w } return m / sumWeights } diff --git a/stat/stat_test.go b/stat/stat_test.go index b8fd9adc..81d7f2ce 100644 --- a/stat/stat_test.go +++ b/stat/stat_test.go @@ -1178,6 +1178,9 @@ func TestMoment(t *testing.T) { if !Panics(func() { Moment(1, make([]float64, 3), make([]float64, 2)) }) { t.Errorf("Moment did not panic with x, weights length mismatch") } + if !Panics(func() { Moment(1, make([]float64, 2), make([]float64, 3)) }) { + t.Errorf("Moment did not panic with x, weights length mismatch") + } } func TestMomentAbout(t *testing.T) {