向量的长度
- 向量的长度又叫向量的模,使用双竖线来包裹向量表示向量的长度
- 下面是二维向量中取模的算法,使用勾股定理即可
image-20200117213429377.png
image-20200117213908453.png
image-20200117215318089.png
单位向量
- 单位向量有无数个
- 二维空间中,有两个特殊的单位向量
- 三维空间中,有三个特殊的单位向量
- n维空间中,有n个特殊的单位向量
image-20200117215614012.png
Python实战案例
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):
"""向量的减法, 返回结果向量"""
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 __truediv__(self, other):
"""返回数量除法结果 self/k"""
return (1 / other) * 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))
print("norm({}) = {}".format(vec, vec.norm()))
print("norm({}) = {}".format(vec2, vec2.norm()))
print("norm({}) = {}".format(zero2, zero2.norm()))
print("normalize {} is {}".format(vec, vec.normalize()))
print(vec.normalize().norm())
print("normalize {} is {}".format(vec2, vec2.normalize()))
print(vec2.normalize().norm())
try:
zero2.normalize()
except ZeroDivisionError:
print("0向量的单位不可求 {}.".format(zero2))