Python面向对象-定义向量

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))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容