#unit vector
def normalized(self):
try:
unit = [ x/self.magnitude() for x in self.coordinates ]
return unit
except ZeroDivisionError:
raise Exception("Can not normalize the zero vector")
#dot product of vector
def dot(self, v):
x = [ x*y for x,y in zip(self.coordinates, v.coordinates)]
return sum(x)
#radians and angle of vector
def angle_with(self, v , degrees = False):
try:
u1 = self.normalized()
u2 = v.normalized()
print(u1, u2)
angle_in_radians = math.acos(u1.dot(u2))
if degrees:
degrees_per_radian = 180. / math.pi
return angle_in_radians * degrees_per_radian
else:
return angle_in_radians
如何在这里使用“点”功能?
答案 0 :(得分:0)
class Vector(object):
def __init__(self, coordinates):
self.coordinates = tuple(coordinates)
self.dimension = len(coordinates)
def normalized(self):
try:
a = 1.0/self.magnitude()
res = [a*x for x in self.coordinates]
return res
except ZeroDivisionError:
raise Exception('your error messsage')
def dot(self, v):
return sum([x * y for x,y in zip(self.coordinates,v.coordinates)])
def angle_with(self, v, in_degree=False):
try:
u1 = Vector(self.normalized())
u2 = Vector(v.normalized())
angle_in_redians = math.acos(u1.dot(u2))
if in_degree:
degrees_per_redian = 180. /pi
return angle_in_redians * degrees_per_redian
else:
return angle_in_redians
#same Vector class and init method
def magnitude(self):
squared_coordinates = [x**2 for x in self.coordinates]
return sqrt(sum(squared_coordinates))
def dot(self, v):
return sum([x * y for x,y in zip(self.coordinates,v.coordinates)])
def angle_with(self, v, in_degree=False):
try:
dot = self.dot(v)
magnitude_v1 = self.magnitude()
magnitude_v2 = v.magnitude()
res = dot/(magnitude_v1*magnitude_v2)
angle_in_redians = math.acos(res)
if in_degree:
degrees_per_redian = 180. /pi
return angle_in_redians * degrees_per_redian
else:
return angle_in_redians