-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.py
More file actions
65 lines (51 loc) · 1.97 KB
/
vector.py
File metadata and controls
65 lines (51 loc) · 1.97 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
'''This program does some computations on vectors in 2D without
using numpy'''
class vector(object):
#vectors can be initialized as a = vector(x_component, y_component). Default = (0,0)
def __init__(self, x = 0, y = 0):
self.x, self.y = x, y
#if a = vector(2,3), print(a) gives output <2,3>
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"
#a==b compares two vectors
def __eq__(self, other):
if self.x==other.x and self.y==other.y:
return True
else:
return False
#a!=b compares two vctors
def __ne__(self,other):
if(self==other):
return False
else:
return True
#-a negates each component
def __neg__(self):
return vector(-self.x, -self.y)
#a + b adds two vectors
def __add__(self, other):
return vector(self.x + other.x, self.y + other.y)
#a-b subtracts two vectors
def __sub__(self, other):
return vector(self.x - other.x, self.y - other.y)
#abs(a) gives the length of a
def __abs__(self):
return ((self.x)**2 + (self.y^2))**0.5
#a*b does scalar multiplication if b is vector or scalar
def __mul__(self, other):
if isinstance(other, vector):
return other.x*self.x + other.y*self.y
elif type(other)!='str':
return vector(other*self.x, other*self.y)
#cross(a,b) does vector product
def cross(self, other):
return vector(self.x*other.y - other.x*self.y)
#measure distance between heads of two vectors
def dist(self, other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
#a**n just repeats scalar multiplication of a with itself
def __pow__(self, c):
return vector(self.x**c, self.y**c)
#converts vector to a complex number
def __complex__(self):
return complex(self.x,self.y)