-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.py
More file actions
69 lines (54 loc) · 2.16 KB
/
vector.py
File metadata and controls
69 lines (54 loc) · 2.16 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
import math
class Vector:
""" a general two-dimensional vector """
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __str__(self):
return f"({self.x} î + {self.y} ĵ)"
def __repr__(self):
return f"Vector({self.x}, {self.y})"
def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
else:
# it doesn't make sense to add anything but two vectors
print(f"we don't know how to add a {type(other)} to a Vector")
raise NotImplementedError
def __sub__(self, other):
if isinstance(other, Vector):
return Vector(self.x - other.x, self.y - other.y)
else:
# it doesn't make sense to add anything but two vectors
print(f"we don't know how to add a {type(other)} to a Vector")
raise NotImplementedError
def __mul__(self, other):
if isinstance(other, int) or isinstance(other, float):
# scalar multiplication changes the magnitude
return Vector(other*self.x, other*self.y)
else:
print("we don't know how to multiply two Vectors")
raise NotImplementedError
def __matmul__(self, other):
# a dot product
if isinstance(other, Vector):
return self.x*other.x + self.y*other.y
else:
print("matrix multiplication not defined")
raise NotImplementedError
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
# we only know how to multiply by a scalar
if isinstance(other, int) or isinstance(other, float):
return Vector(self.x/other, self.y/other)
def __abs__(self):
return math.sqrt(self.x**2 + self.y**2)
def __neg__(self):
return Vector(-self.x, -self.y)
def cross(self, other):
# a vector cross product -- we return the magnitude, since it will
# be in the z-direction, but we are only 2-d
return abs(self.x*other.y - self.y*other.x)