-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistance.go
90 lines (79 loc) · 1.56 KB
/
distance.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package kmeans
import (
"math"
)
// L1
func L1(a, b Node) (float64) {
distance := 0.
for i := range a {
distance += math.Abs(a[i] - b[i])
}
return distance
}
// L2
func L2(a, b Node) (float64) {
return math.Sqrt(L2s(a, b))
}
// L2 squared
func L2s(a, b Node) (float64) {
distance := 0.
for i := range a {
distance += (a[i] - b[i])*(a[i] - b[i])
}
return distance
}
// Lp returns Lp norm
func Lp(p float64) (Distance) {
return func (a, b Node) float64 {
distance := 0.
for i := range a {
distance += math.Pow(math.Abs(a[i]-b[i]), p)
}
return math.Pow(distance, 1/p)
}
}
// Lpw returns weighted Lp norm
// Yeah I know, no checks... use it with caution!
func Lpw(w Node, p float64) (Distance) {
return func (a, b Node) float64 {
distance := 0.
for i := range a {
distance += w[i] * math.Pow(math.Abs(a[i]-b[i]), p)
}
return math.Pow(distance, 1/p)
}
}
// infinity norm distance (l_inf distance)
func ChebyshevDistance(a, b Node) (float64) {
distance := 0.
for i := range a {
if math.Abs(a[i]-b[i]) >= distance {
distance = math.Abs(a[i] - b[i])
}
}
return distance
}
func HammingDistance(a, b Node) (float64) {
distance := 0.
for i := range a {
if a[i] != b[i] {
distance++
}
}
return distance
}
func BrayCurtisDistance(a, b Node) (float64) {
n, d := 0., 0.
for i := range a {
n += math.Abs(a[i] - b[i])
d += math.Abs(a[i] + b[i])
}
return n/d
}
func CanberraDistance(a, b Node) (float64) {
distance := 0.
for i := range a {
distance += math.Abs(a[i]-b[i]) / (math.Abs(a[i]) + math.Abs(b[i]))
}
return distance
}