Python面向对象-定义向量

2021-04-11  本文已影响0人  九章9405
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))
上一篇 下一篇

猜你喜欢

热点阅读