-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.go
76 lines (59 loc) · 1.3 KB
/
vector.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
package vector
import (
"errors"
"math"
)
var (
ErrAdd = errors.New("Can't add the vector check and see that they have the same length")
)
// Vector represents a vector
type Vector []float64
// New ...
func New(data ...float64) Vector {
return data
}
// Len returns the lenght of a vector
func (v Vector) Len() int { return len(v) }
// Magnitude computes the Magnitude of the vector
func (v Vector) Magnitude() float64 {
var square_sum float64
for _, e := range v {
square_sum = square_sum + math.Pow(e, 2)
}
return math.Pow(square_sum, 0.5)
}
// Is_Unit return if a vector is a unit vector or not
func (v Vector) Is_Unit() bool {
if v.Magnitude() == 1.0 {
return true
}
return false
}
// Add added two vector
func (v Vector) Add(addvector Vector) (sum Vector, err error) {
if v.Len() != addvector.Len() {
return nil, ErrAdd
}
for i := 0; i < v.Len(); i++ {
sum = append(sum, v[i]+addvector[i])
}
return
}
// Sub subtracts two vector
func (v Vector) Sub(addvector Vector) (sum Vector, err error) {
if v.Len() != addvector.Len() {
return nil, ErrAdd
}
for i := 0; i < v.Len(); i++ {
sum = append(sum, v[i]-addvector[i])
}
return
}
// Scalar ..
func (v Vector) Scalar(number float64) Vector {
vec := make(Vector, len(v))
for i, n := range v {
vec[i] = n * number
}
return vec
}