python 中自己写方法 计算向量长度 / 实现向量归一化

2019-04-13 15:35发布

# coding=utf-8 import math class Vector(object): """docstring for Vector""" """根据坐标轴列表输入 创建向量, 并创建该向量所处的空间维度""" def __init__(self, coordinates): super(Vector, self).__init__() try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') # '''能够使python的内置print函数 输出向量坐标轴''' def __str__(self): return 'Vector: {}'.format(self.coordinates) def __eq__(self, v): return self.coordinates == v.coordinates # 计算向量长度 def calculateSize(self): result = 0 num = len(self.coordinates) for i in range(num): result +=self.coordinates[i] * self.coordinates[i] result = math.sqrt(result) return round(result,3) # 将向量归一化 def standardizaiton(self): size = self.calculateSize() new_corrdinate = [round(x/size,3) for x in self.coordinates] return Vector(new_corrdinate) myVector = Vector([-0.221,7.437]) myVector2 = Vector([5.581,-2.136]) myVector3 = Vector([8.813,-1.331,-6.247]) myVector4 = Vector([1.996,3.108,-4.554]) print myVector.calculateSize() print myVector2.standardizaiton() print myVector3.calculateSize() print myVector4.standardizaiton() # 输出结果 # 7.44 # Vector: (0.934, -0.357) # 10.884 # Vector: (0.34, 0.53, -0.777) # [Finished in 0.1s] 优化 # 计算向量长度 def magnitude(self): coordinates_squared = [x**2 for x in self.coordinates] return math.sqrt(sum(coordinates_squared)) # 将向量归一化 def normalized(self): try: magnitude = self.magnitude() return [x *(1./magnitude) for x in self.coordinates] except ZeroDivisionError: raise Exception('Cannot normalized the zero myVector2') myVector = Vector([-0.221,7.437]) myVector2 = Vector([5.581,-2.136]) myVector3 = Vector([0,0]) print myVector.magnitude() print myVector2.normalized() print myVector3.normalized() # 输出 # 7.44028292473 # [0.9339352140866403, -0.35744232526233] # Traceback (most recent call last): # File "/Users/Scarlett/Desktop/MovieProject/Vector.py", line 47, in # print myVector3.normalized() # File "/Users/Scarlett/Desktop/MovieProject/Vector.py", line 38, in normalized # raise Exception('Cannot normalized the zero myVector2') # Exception: Cannot normalized the zero myVector2 # [Finished in 0.1s with exit code 1]