Fixed check for zero probability value in JensenShannon and updated test.

This commit is contained in:
btracey
2014-09-16 23:46:39 -07:00
parent 6f420f1ff0
commit 1da795789e
2 changed files with 7 additions and 1 deletions

View File

@@ -402,9 +402,11 @@ func JensenShannon(p, q []float64) float64 {
for i, v := range p {
qi := q[i]
m := 0.5 * (v + qi)
if m != 0 {
if v != 0 {
// add kl from p to m
js += 0.5 * v * (math.Log(v) - math.Log(m))
}
if qi != 0 {
// add kl from q to m
js += 0.5 * qi * (math.Log(qi) - math.Log(m))
}

View File

@@ -357,6 +357,10 @@ func TestJensenShannon(t *testing.T) {
js1 := 0.5*KullbackLeibler(p, m) + 0.5*KullbackLeibler(q, m)
js2 := JensenShannon(p, q)
if math.IsNaN(js2) {
t.Errorf("In case %v, JS distance is NaN", i)
}
if math.Abs(js1-js2) > 1e-14 {
t.Errorf("JS mismatch case %v. Expected %v, found %v.", i, js1, js2)
}