...
1 package geo
2
3 import (
4 "math"
5 )
6
7
8 type Vector []float64
9
10
11 func NewVector(components ...float64) Vector {
12 return components
13 }
14
15
16 func NewVectorFromProperties(length float64, angleInRadians float64) Vector {
17 return NewVector(
18 length*math.Sin(angleInRadians),
19 length*math.Cos(angleInRadians),
20 )
21 }
22
23
24 func (a Vector) AddLength(length float64) Vector {
25 return a.Unit().Multiply(a.Length() + length)
26 }
27
28 func (a Vector) Add(b Vector) Vector {
29 c := []float64{}
30 for i := 0; i < len(a); i++ {
31 c = append(c, a[i]+b[i])
32 }
33 return c
34 }
35
36 func (a Vector) Minus(b Vector) Vector {
37 c := []float64{}
38 for i := 0; i < len(a); i++ {
39 c = append(c, a[i]-b[i])
40 }
41 return c
42 }
43
44 func (a Vector) Multiply(v float64) Vector {
45 c := []float64{}
46 for i := 0; i < len(a); i++ {
47 c = append(c, a[i]*v)
48 }
49 return c
50 }
51
52 func (a Vector) Length() float64 {
53 sum := 0.0
54 for _, comp := range a {
55 sum += comp * comp
56 }
57 return math.Sqrt(sum)
58 }
59
60
61 func (a Vector) Unit() Vector {
62 return a.Multiply(1 / a.Length())
63 }
64
65 func (a Vector) ToPoint() *Point {
66 return &Point{a[0], a[1]}
67 }
68
69
70 func getNormalVector(x1, y1, x2, y2 float64) (float64, float64) {
71 return y1 - y2, x2 - x1
72 }
73
74 func GetUnitNormalVector(x1, y1, x2, y2 float64) (float64, float64) {
75 normalX, normalY := getNormalVector(x1, y1, x2, y2)
76 length := EuclideanDistance(x1, y1, x2, y2)
77 return normalX / length, normalY / length
78 }
79
80 func (a Vector) Radians() float64 {
81 return float64(float32(math.Atan2(a[1], a[0])))
82 }
83
84 func (a Vector) Degrees() float64 {
85 return a.Radians() * 180 / math.Pi
86 }
87
88 func (a Vector) Reverse() Vector {
89 return a.Multiply(-1)
90 }
91
View as plain text