import math
class Vector:
EPSION = 1e-8 # 1/10^8,数字足够的小
def __init__(self, my_list):
self._values = my_list
@classmethod
def zero(cls, dim):
"""返回一个dim维的零向量"""
return cls([0] * dim)
def norm(self):
"""返回向量的模"""
return math.sqrt(sum(e ** 2 for e in self))
def normalize(self):
"""返回向量的单位向量"""
if self.norm() < self.EPSION:
raise ZeroDivisionError("向量不可以为0")
return Vector(self._values) / self.norm()
def __add__(self, other):
"""向量的加法,返回结果向量"""
assert len(self) == len(other), \
"向量的长度错误,向量之间长度必须是相等的"
return Vector([a + b for a, b in zip(self, other)])
def __sub__(self, other):
"""向量的减