• 向量Vector


    import math
    
    
    class Vector:
        """向量"""
    
        @classmethod
        def zero(cls, dim):
            """dim长度的0向量"""
            return cls([0] * dim)
    
        def __init__(self, lst):
            self._values = list(lst)
    
        def __repr__(self):
            print('Vector({})'.format(self._values))
    
        def __str__(self):
            return '({})'.format(', '.join(str(e) for e in self._values))
    
        def __len__(self):
            return len(self._values)
    
        def dot(self, other):
            """向量点乘,返回结果标量"""
            assert len(self) == len(other), 
                "Error in dot product. Length of vectors must be same."
            return sum(a * b for a, b in zip(self, other))
    
        def normalize(self):
            """单位向量、归一化"""
            if self.norm() < 1e-8:
                raise ZeroDivisionError("Normalize error! norm is zero.")
            return Vector(self) / self.norm()
    
        def norm(self):
            """模"""
            return math.sqrt(sum(a ** 2 for a in self))
    
        def __pos__(self):
            """返回向量取正的结果向量 positive """
            return 1 * self
    
        def __neg__(self):
            """返回向量取负的结果向量 negative """
            return -1 * self
    
        def __getitem__(self, index):
            return self._values[index]
    
        def __add__(self, other):
            """向量加法,返回结果向量"""
            assert len(self) == len(other), 
                "Error in adding. Length of vectors must be same."
            return Vector([a + b for a, b in zip(self, other)])
    
        def __sub__(self, other):
            """向量减法,返回结果向量"""
            assert len(self) == len(other), 
                "Error in subtracting. Length of vectors must be same."
            return Vector([a - b for a, b in zip(self, other)])
    
        def __mul__(self, k):
            """数乘"""
            return Vector([a * k for a in self])
    
        def __rmul__(self, k):
            return self * k
    
        def __truediv__(self, k):
            return self * (1 / k)
    
        def __iter__(self):
            return self._values.__iter__()
    
    
  • 相关阅读:
    Angular语法(三)——数据绑定
    Angular语法(二)——模板语法
    Angular语法(一)——展示数据
    Angular常用指令
    windows下启动redis
    WPF实现弹幕
    微信获得用户信息
    拉普拉斯变换
    Convolutional Neural Networks on Graphs with Fast Localized Spectral Filtering
    Python之并行
  • 原文地址:https://www.cnblogs.com/fly-book/p/13389824.html
Copyright © 2020-2023  润新知