1 """
2 This module implements the Vector object. Which has several of
3 2D vector features such dot product, adding, project and angle.
4 It also overloads many commom math operator
5 """
6
7 import math
8
10 """
11 Finds out if a variable is a numeric one
12 """
13 if isinstance(obj, (int, long, float)):
14 return True
15 else:
16 return False
17
19 """
20 Vector class: Objects of this class have several of
21 2D vector implementations such dot product, adding, project and angle.
22 It also overloads many commom math operator
23 """
24
26 """
27 Creates a new vector
28 """
29 if _is_numeric(a):
30
31 self.x = a
32 self.y = b
33 else:
34
35 self.x = b[0] - a[0]
36 self.y = b[1] - a[1]
37
39 if index == 0:
40 return self.x
41 elif index == 1:
42 return self.y
43 else:
44 raise IndexError
45
47 return Vector(self.x + other.x, self.y + other.y)
48
50 return Vector(self.x - other.x, self.y - other.y)
51
53 try:
54 other = other - 0
55 except:
56 raise TypeError, "Only scalar multiplication is supported."
57 return Vector( other * self.x, other * self.y )
58
61
63 return Vector( self.x / other, self.y / other )
64
66 return Vector(-self.x, -self.y)
67
70
72 return '(%s, %s)' % (self.x, self.y)
73
75 return '(%s, %s)' % (self.x, self.y)
76
79
80 - def dot(self, vector):
81 """
82 Return the dot product of two vectors
83 """
84 return self.x * vector.x + self.y * vector.y
85
87 """
88 Return the cross product of two vectors
89 """
90 return self.x * vector.y - self.y * vector.x
91
93 """
94 Return the vector's length
95 """
96 return math.sqrt( self.dot(self) )
97
99 """
100 Return the vector that is perpenticular of this
101 """
102 return Vector(-self.y, self.x)
103
105 """
106 Return the vector's unit(length one)
107 """
108 return self / self.length()
109
111 """
112 Return the projection of this vector on another
113 """
114 return self.dot(vector.unit()) * vector.unit()
115
116 - def angle(self, vector=None):
117 """
118 Return the angle created by this vector and another of the vector
119 (1,0) if given None
120 """
121 if vector == None:
122 vector = Vector(1,0)
123 return math.acos((self.dot(vector))/(self.length() * vector.length()))
124
126 """
127 Return the angle created by this vector and another of the vector
128 (1,0) if given None. Angle in degrees
129 """
130 return (self.angle(vector) * 180) /math.pi
131