-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathvector2d.py
More file actions
69 lines (51 loc) · 2.37 KB
/
vector2d.py
File metadata and controls
69 lines (51 loc) · 2.37 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
# https://scipython.com/book2/chapter-4-the-core-python-language-ii/examples/a-2d-vector-class/
import math
class Vector2D:
"""A two-dimensional vector with Cartesian coordinates."""
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
"""Human-readable string representation of the vector."""
return '({:g}, {:g})'.format(self.x, self.y)
def __repr__(self):
"""Unambiguous string representation of the vector."""
return repr((self.x, self.y))
def dot(self, other):
"""The scalar (dot) product of self and other. Both must be vectors."""
if not isinstance(other, Vector2D):
raise TypeError('Can only take dot product of two Vector2D objects')
return self.x * other.x + self.y * other.y
# Alias the __matmul__ method to dot so we can use a @ b as well as a.dot(b).
__matmul__ = dot
def __sub__(self, other):
"""Vector subtraction."""
return Vector2D(self.x - other.x, self.y - other.y)
def __add__(self, other):
"""Vector addition."""
return Vector2D(self.x + other.x, self.y + other.y)
def __mul__(self, scalar):
"""Multiplication of a vector by a scalar."""
if isinstance(scalar, int) or isinstance(scalar, float):
return Vector2D(self.x*scalar, self.y*scalar)
raise NotImplementedError('Can only multiply Vector2D by a scalar')
def __rmul__(self, scalar):
"""Reflected multiplication so vector * scalar also works."""
return self.__mul__(scalar)
def __neg__(self):
"""Negation of the vector (invert through origin.)"""
return Vector2D(-self.x, -self.y)
def __truediv__(self, scalar):
"""True division of the vector by a scalar."""
return Vector2D(self.x / scalar, self.y / scalar)
def __mod__(self, scalar):
"""One way to implement modulus operation: for each component."""
return Vector2D(self.x % scalar, self.y % scalar)
def __abs__(self):
"""Absolute value (magnitude) of the vector."""
return math.sqrt(self.x**2 + self.y**2)
def distance_to(self, other):
"""The distance between vectors self and other."""
return abs(self - other)
def to_polar(self):
"""Return the vector's components in polar coordinates."""
return self.__abs__(), math.atan2(self.y, self.x)