-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRealVector.go
114 lines (87 loc) · 2.23 KB
/
RealVector.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package LinearAlgebra
import (
"errors"
"fmt"
"math"
)
type RealVector struct {
nums []float64
}
func NewRealVector(nums []float64) *RealVector {
if nums == nil {
return &RealVector{[]float64{}}
}
return &RealVector{nums: nums}
}
func(v RealVector) Get() []float64 {
return v.nums
}
func (v RealVector) Add(other *RealVector) (*RealVector,error) {
if len(v.nums) != len(other.nums) {
return nil, errors.New("vectors not in the same set")
}
newVec := &RealVector{[]float64{}}
for key, val := range v.nums {
newVec.nums = append(newVec.nums, other.nums[key]+ val)
}
return newVec,nil
}
func (v RealVector) Minus(other *RealVector) (*RealVector,error) {
if len(v.nums) != len(other.nums) {
return nil, errors.New("vectors not in the same set")
}
newVec := &RealVector{[]float64{}}
for key, val := range v.nums {
newVec.nums = append(newVec.nums, val - other.nums[key])
}
return newVec,nil
}
func (v RealVector) Dot(other *RealVector) (float64,error) {
if len(v.nums) != len(other.nums) {
return 0, errors.New("vectors not in the same set")
}
var prod float64
for key, val := range v.nums {
prod += val * other.nums[key]
}
return prod,nil
}
//only works on vectors in R^3
func (v RealVector) Cross(other *RealVector) (*RealVector,error) {
if len(v.nums) != 3 || len(other.nums) != 3 {
return nil, errors.New("atleast one vector is not in R^3")
}
NewVec := &RealVector{[]float64{}}
NewVec.nums = append(NewVec.nums, v.nums[1]*other.nums[2] - other.nums[1]*v.nums[2])
NewVec.nums = append(NewVec.nums, v.nums[2]*other.nums[0] - other.nums[2]*v.nums[0])
NewVec.nums = append(NewVec.nums, v.nums[0]*other.nums[1] - other.nums[0]*v.nums[1])
return NewVec,nil
}
func (v RealVector) Equal(other *RealVector) bool {
if len(v.nums) != len(other.nums) {
return false
}
for key, val := range v.nums {
if !equal(val,other.nums[key]) {
fmt.Println(val," : ",other.nums[key])
return false
}
}
return true
}
func(v RealVector) Norm() float64 {
var norm float64
for _, val := range v.nums {
norm += val*val
}
return math.Sqrt(norm)
}
func(v RealVector) String() string {
sVec := "["
for _, val := range v.nums {
sVec += fmt.Sprintf(" %f,",val)
}
sVec = sVec[0:len(sVec)-1]
sVec += " ]"
return sVec
}