概念
对于任意一个向量,都存在一个向量,满足:
对于任意一个向量,都存在一个一个向量,满足:
证明零向量定理
所以要证明,得出结论
python代码实现零向量
class Vector:
def __init__(self, my_list):
self._values = my_list
@classmethod
def zero(cls, dim):
"""返回一个dim维的零向量"""
return cls([0]*dim)
def __add__(self, other):
"""向量的加法,返回结果向量"""
assert len(self) == len(other), \
"向量的长度错误,向量之间长度必须是相等的"
return Vector([a + b for a, b in zip(self, other)])
def __sub__(self, other):
"""向量的减法, 返回结果向量"""
assert len(self) == len(other), \
"向量的长度错误,向量之间长度必须是相等的"
return Vector([a - b for a, b in zip(self, other)])
def __mul__(self, other):
"""返回数量乘法的结果向量, 只定义了self * other"""
return Vector([other * e for e in self])
def __rmul__(self, other):
"""返回向量的右乘方法, 只定义了 other * self"""
return Vector([other * e for e in self])
def __pos__(self):
"""返回向量取正的结果向量"""
return 1 * self
def __neg__(self):
"""返回向量取负的向量结果"""
return -1 * self
def __iter__(self):
"""返回向量的迭代器"""
return self._values.__iter__()
def __getitem__(self, item):
"""取向量的第index元素"""
return self._values[item]
def __len__(self):
"""返回向量的长度"""
return len(self._values)
def __repr__(self):
return "Vector ({})".format(self._values)
def __str__(self):
return "({})".format(", ".join(str(e) for e in self._values))
if __name__ == '__main__':
vec = Vector([5, 2])
print(vec)
print(len(vec))
vec2 = Vector([3, 1])
print("{} + {} = {}".format(vec, vec2, vec + vec2))
print("{} - {} = {}".format(vec, vec2, vec - vec2))
print("{} * {} = {}".format(vec, 3, vec * 3))
print("{} * {} = {}".format(3, vec, 3 * vec))
print("+{} = {}".format(vec, +vec))
print("-{} = {}".format(vec, -vec))
# 创建一个二维的0向量
zero2 = Vector.zero(2)
print("{} + {} = {}".format(vec, zero2, vec + zero2)) ###########
# 输出结果
(5, 2)
2
(5, 2) + (3, 1) = (8, 3)
(5, 2) - (3, 1) = (2, 1)
(5, 2) * 3 = (15, 6)
3 * (5, 2) = (15, 6)
+(5, 2) = (5, 2)
-(5, 2) = (-5, -2)
(5, 2) + (0, 0) = (5, 2) ############
网友评论