fix weighted covariance implementation

Weighted covariance accidentally used squared weights.  Added a test
case and fixed implementation.
This commit is contained in:
Jonathan J Lawlor
2014-12-23 21:41:15 -05:00
parent 93f33faa81
commit fb2fe6268d
2 changed files with 9 additions and 3 deletions

View File

@@ -236,10 +236,10 @@ func Covariance(x, y, weights []float64) float64 {
w := weights[i] w := weights[i]
yv := y[i] yv := y[i]
wxd := w * (xv - xu) wxd := w * (xv - xu)
wyd := w * (yv - yu) yd := (yv - yu)
ss += wxd * wyd ss += wxd * yd
xcompensation += wxd xcompensation += wxd
ycompensation += wyd ycompensation += w * yd
sumWeights += w sumWeights += w
} }
// xcompensation and ycompensation are from Chan, et. al. // xcompensation and ycompensation are from Chan, et. al.

View File

@@ -128,6 +128,12 @@ func TestCovariance(t *testing.T) {
weights: []float64{1, 1.5, 1}, weights: []float64{1, 1.5, 1},
ans: 3.2, ans: 3.2,
}, },
{
p: []float64{1, 4, 9},
q: []float64{1, 4, 9},
weights: []float64{1, 1.5, 1},
ans: 13.142857142857146,
},
} { } {
c := Covariance(test.p, test.q, test.weights) c := Covariance(test.p, test.q, test.weights)
if math.Abs(c-test.ans) > 1e-14 { if math.Abs(c-test.ans) > 1e-14 {