-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.py
101 lines (90 loc) · 2.53 KB
/
vector.py
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
93
94
95
96
97
98
99
100
101
#Alice Forehand
#Robert Pienta
#Eric Reed
from math import acos, sqrt, pi, atan2
class Vector:
"""A simple 2d vector
>>> v1 = Vector(1,0)
>>> v2 = Vector(0,1)
>>> print(v1.add(v2))
(1, 1)
>>> print(v1 + v2)
(1, 1)
>>> print(v1.subtract(v2))
(1, -1)
>>> print(v1 - v2)
(1, -1)
>>> print(v1 / 2)
(0.5, 0.0)
>>> print(v1 * 3)
(3, 0)
>>> v1.magnitude()
1.0
>>> v2.magnitude()
1.0
>>> v1.dotProduct(v2)
0
>>> v2.dotProduct(v1)
0
>>> v1.dotProduct(v1)
1
>>> v2.dotProduct(v2)
1
>>> print(v1)
(1, 0)
>>> v1.angleBetween(v2)*180/pi
90.0
>>> print(v1.projection(v2))
(0.0, 0.0)
>>> print(v1.truncate(.5))
(0.5, 0.0)
>>> v3 = Vector(1,1)
>>> print(v3.truncate(1))
(0.707106781187, 0.707106781187)
"""
def __init__(self, xi, yi):
self.x = xi
self.y = yi
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
def add(self, v1):
return Vector(self.x+v1.x, self.y+v1.y)
def __add__(self, v1):
return Vector(self.x+v1.x, self.y+v1.y)
def subtract(self, v1):
return Vector(self.x-v1.x, self.y-v1.y)
def __sub__(self, v1):
return Vector(self.x-v1.x, self.y-v1.y)
def __truediv__(self, scalar):
return Vector(self.x/scalar, self.y/scalar)
def __mul__(self, scalar):
return Vector(self.x*scalar, self.y*scalar)
def scalarMult(self, scalar):
return Vector(self.x*scalar, self.y*scalar)
def magnitude(self):
return sqrt(self.x*self.x + self.y*self.y)
def magnitudeSansRoot(self):
return self.x*self.x + self.y*self.y
def dotProduct(self, v1):
return self.x*v1.x + self.y*v1.y
def angleBetween(self, v1):
t = self.magnitude()*v1.magnitude()
if(not t == 0):
return acos(self.dotProduct(v1)/(self.magnitude()*v1.magnitude()))
return 0
def angleBetweenAtan(self, v1):
return atan2(self.y, self.x) - atan2(v1.y, v1.x)
def projection(self, v1):
return v1.scalarMult(self.dotProduct(v1)/v1.magnitudeSansRoot())
def truncate(self, scalar):
mag = self.magnitude()
if(mag > scalar):
return Vector(self.x/mag*scalar, self.y/mag*scalar)
return Vector(self.x, self.y)
def vec2tuple(self):
return (self.x, self.y)
def normal(self):
return Vector(-1 * self.y, self.x)
if __name__ == "__main__":
import doctest
doctest.testmod()