from math import sqrt,cos,acos
class Vector:
def __init__(self, x):
"""
定义向量:Vector(x),其中x是一个列表
"""
self.x = tuple(x)
def __str__(self):
"""
让print的时候显示Vector([x1,x2,x3,...])
"""
return 'Vector({0})'.format(list(self.x))
def __add__(self, other):
z = list(map(lambda x, y: x + y, self.x, other.x))
return Vector(z)
def __sub__(self, other):
z = list(map(lambda x, y: x - y, self.x, other.x))
return Vector(z)
def dot(self, other):
"""计算向量点乘"""
z = sum(list(map(lambda x, y: x * y, self.x, other.x)))
return z
def __mul__(self,scalar):
"""定义向量乘以标量"""
z = list(map(lambda x:x*scalar,self.x))
return Vector(z)
def __rmul__(self,scalar):
"""定义向量乘以标量"""
return self*scalar
@property
def norm(self):
"""计算向量的模长"""
z = sqrt(self.dot(self))
return z
@property
def dim(self):
"""计算向量的维度"""
return len(self.x)
def cos_alpha(self, other):
"""计算两个向量夹角的余弦值"""
cos_alpha = (self.dot(other)) / (self.norm * other.norm)
return cos_alpha
def alpha(self,other):
"""计算两个向量的夹角对于的弧度值"""
return acos(self.cos_alpha(other))
a = Vector([1,1,3])
b = Vector([2,1,1])
#计算向量的加法、乘法
print(a+b)
print(a-b)
#计算向量*标量
print(4*a)
#计算向量的点乘
print(a.dot(b))
#计算维度
print(a.dim)
#计算向量的模长
print(a.norm)
#计算向量间的夹角余弦
print(Vector.cos_alpha(a,b))
print(a.cos_alpha(b))
#计算向量的夹角
print(a.alpha(b))
Python面向对象-定义向量
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 注:本文所有代码均经过Python 3.7实际运行检验,保证其严谨性。 本文阅读时间约为2分钟。 列表方法.sor...
- 本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处...
- 1.类和对象 我们把对象比作一个“饼干”,类就是制作这个饼干的“模具”。 我们通过类定义不同数据类型的属性(数据)...
- 注:本文所有代码均经过Python 3.7实际运行检验,保证其严谨性。 本文阅读时间约为3分钟。 什么是类 类(c...