forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distance.go
36 lines (27 loc) · 842 Bytes
/
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
// distance.go
// Find Euclidean distance between two points
// author(s) [Chetan Patil](https://github.com/Chetan07j)
// Package geometry contains geometric algorithms
package geometry
import (
"errors"
"math"
)
// EuclideanPoint defines a point with x and y coordinates.
type EuclideanPoint []float64
var ErrDimMismatch = errors.New("mismatched dimensions")
// EuclideanDistance returns the Euclidean distance between points in
// any `n` dimensional Euclidean space.
func EuclideanDistance(p1 EuclideanPoint, p2 EuclideanPoint) (float64, error) {
n := len(p1)
if len(p2) != n {
return -1, ErrDimMismatch
}
var total float64 = 0
for i, x_i := range p1 {
// using Abs since the value could be negative but we require the magnitude
diff := math.Abs(x_i - p2[i])
total += diff * diff
}
return math.Sqrt(total), nil
}