1
0
mirror of https://github.com/sjwhitworth/golearn.git synced 2025-04-26 13:49:14 +08:00

Add manhattan distance.

This commit is contained in:
Bert Chang 2014-05-03 22:27:34 +08:00
parent 6517c838c4
commit b045cf83a5
2 changed files with 54 additions and 0 deletions

View File

@ -0,0 +1,27 @@
package pairwise
import (
"math"
"github.com/gonum/matrix/mat64"
)
type Manhattan struct{}
func NewManhattan() *Manhattan {
return &Manhattan{}
}
func (self *Manhattan) Distance(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
subVector := mat64.NewDense(0, 0, nil)
subVector.Sub(vectorX, vectorY)
r, _ := subVector.Dims()
result := .0
for i := 0; i < r; i++ {
result += math.Abs(subVector.At(i, 0))
}
return result
}

View File

@ -0,0 +1,27 @@
package pairwise
import (
"testing"
"github.com/gonum/matrix/mat64"
. "github.com/smartystreets/goconvey/convey"
)
func TestManhattan(t *testing.T) {
manhattan := NewManhattan()
Convey("Given two vectors", t, func() {
vectorX := mat64.NewDense(3, 1, []float64{2, 2, 3})
vectorY := mat64.NewDense(3, 1, []float64{1, 4, 5})
Convey("When calculating distance", func() {
result := manhattan.Distance(vectorX, vectorY)
Convey("The result should be 5", func() {
So(result, ShouldEqual, 5)
})
})
})
}