|
| 1 | +import math |
| 2 | + |
| 3 | + |
| 4 | +class Vector: |
| 5 | + """ a general two-dimensional vector """ |
| 6 | + |
| 7 | + def __init__(self, x, y): |
| 8 | + self.x = x |
| 9 | + self.y = y |
| 10 | + |
| 11 | + def __eq__(self, other): |
| 12 | + return self.x == other.x and self.y == other.y |
| 13 | + |
| 14 | + def __str__(self): |
| 15 | + return f"({self.x} î + {self.y} ĵ)" |
| 16 | + |
| 17 | + def __repr__(self): |
| 18 | + return f"Vector({self.x}, {self.y})" |
| 19 | + |
| 20 | + def __add__(self, other): |
| 21 | + if isinstance(other, Vector): |
| 22 | + return Vector(self.x + other.x, self.y + other.y) |
| 23 | + else: |
| 24 | + # it doesn't make sense to add anything but two vectors |
| 25 | + print(f"we don't know how to add a {type(other)} to a Vector") |
| 26 | + raise NotImplementedError |
| 27 | + |
| 28 | + def __sub__(self, other): |
| 29 | + if isinstance(other, Vector): |
| 30 | + return Vector(self.x - other.x, self.y - other.y) |
| 31 | + else: |
| 32 | + # it doesn't make sense to add anything but two vectors |
| 33 | + print(f"we don't know how to add a {type(other)} to a Vector") |
| 34 | + raise NotImplementedError |
| 35 | + |
| 36 | + def __mul__(self, other): |
| 37 | + if isinstance(other, int) or isinstance(other, float): |
| 38 | + # scalar multiplication changes the magnitude |
| 39 | + return Vector(other*self.x, other*self.y) |
| 40 | + else: |
| 41 | + print("we don't know how to multiply two Vectors") |
| 42 | + raise NotImplementedError |
| 43 | + |
| 44 | + def __matmul__(self, other): |
| 45 | + # a dot product |
| 46 | + if isinstance(other, Vector): |
| 47 | + return self.x*other.x + self.y*other.y |
| 48 | + else: |
| 49 | + print("matrix multiplication not defined") |
| 50 | + raise NotImplementedError |
| 51 | + |
| 52 | + def __rmul__(self, other): |
| 53 | + return self.__mul__(other) |
| 54 | + |
| 55 | + def __truediv__(self, other): |
| 56 | + # we only know how to multiply by a scalar |
| 57 | + if isinstance(other, int) or isinstance(other, float): |
| 58 | + return Vector(self.x/other, self.y/other) |
| 59 | + |
| 60 | + def __abs__(self): |
| 61 | + return math.sqrt(self.x**2 + self.y**2) |
| 62 | + |
| 63 | + def __neg__(self): |
| 64 | + return Vector(-self.x, -self.y) |
| 65 | + |
| 66 | + def cross(self, other): |
| 67 | + # a vector cross product -- we return the magnitude, since it will |
| 68 | + # be in the z-direction, but we are only 2-d |
| 69 | + return abs(self.x*other.y - self.y*other.x) |
0 commit comments