-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector.py
More file actions
92 lines (70 loc) · 2.54 KB
/
Vector.py
File metadata and controls
92 lines (70 loc) · 2.54 KB
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
import math
from decimal import Decimal, getcontext
getcontext().pred = 30
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple(Decimal(x) for x in coordinates)
self.dimension = len(coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def __eq__(self, v):
return self.coordinates == v.coordinates
def addition(self, v):
# Better: Use list comprehension
values = []
if self.dimension != v.dimension:
return
for i in range (0,self.dimension):
values.append(self.coordinates[i] + v.coordinates[i])
return Vector(values)
def substraction(self, v):
values = []
if self.dimension != v.dimension:
return
for i in range (0,self.dimension):
values.append(self.coordinates[i] - v.coordinates[i])
return Vector(values)
def multiplyScalar(self, scalar):
values = []
for i in range(0, self.dimension):
values.append(self.coordinates[i] * Decimal(scalar))
return Vector(values)
def getMagnitude(self):
value = 0
for i in range(0, self.dimension):
value += self.coordinates[i] ** 2
return Decimal(math.sqrt(value))
def normalize(self):
return self.multiplyScalar(Decimal(1.0) / self.getMagnitude())
def dotProduct(self, v):
value = Decimal(0.0)
for i in range(0, self.dimension):
value += self.coordinates[i] * v.coordinates[i]
return value
def angle(self, v):
return math.acos(self.dotProduct(v) / (self.getMagnitude() * v.getMagnitude()))
def checkIfParallel(self, v):
return(self.isZero() or v.isZero()
or self.angle(v) == 0
or self.angle(v) == math.pi )
def checkIfOrt(self, v):
tolerance = 1e-10
if abs(self.dotProduct(v)) < tolerance:
return True
else:
return False
def isZero(self):
return self.getMagnitude() < 1e-10
def getProjection(self, v):
unitVector = v.normalize()
return (unitVector.multiplyScalar(self.dotProduct(unitVector)))
v1 = Vector([3.039 , 1.879])
v2 = Vector([ 0.825 , 2.036])
print(v1.getProjection(v2))