美文网首页
Python面向对象-定义向量

Python面向对象-定义向量

作者: 九章9405 | 来源:发表于2021-04-11 18:18 被阅读0次
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全栈之路系列之面向对象基础

    面向对象基本介绍 Python编程方式: 面向过程编程 面向函数编程 面向对象编程 名称定义: 如果函数没有在类中...

  • python面向对象程序设计(OOP)

    python面向对象程序设计(OOP) 类定义语法class className: 在python中可以...

  • python面向对象学习笔记-01

    学习笔记 # 0,OOP-Python面向对象 - Python的面向对象 - 面向对象编程 - 基础 -...

  • python 类定义和属性

    类定义 python是一门面向对象的语言,面向对象最重要的概念就是类(Class)和实例(Instance), 【...

  • Python 面向对象编程

    Python 面向对象编程(一) Python 面向对象编程(一) 虽然Python是解释性语言,但是它是面向对象...

  • Python环境搭建

    Day2Python学习笔记+开发环境搭载 Python面向对象特性: 类的定义 类定义class关键字 多重继承...

  • python3教程

    python3--定义:python是一门解释语言不同于c/c++,他们是面向过程和面向对象的两门语言python...

  • 面向对象编程

    面向对象编程 概念:oop,Python内一切结为对象 类Class定义class ClassName(objec...

  • python基础-02

    Python 面向对象 python是一门面向对象的语言 Python内置类属性 python对象销毁(垃圾回收)...

网友评论

      本文标题:Python面向对象-定义向量

      本文链接:https://www.haomeiwen.com/subject/orxzkltx.html