每天学一点新知识

向量的相乘点乘的定义和计算公式_线性代数_day6

2020-01-20  本文已影响0人  FANDX

向量的相乘

image-20200118222543074.png image-20200118222733397.png

证明:\vec{u}*\vec{v} = ||\vec{u}||*||\vec{v}||*cos\theta

image-20200118231406164.png image-20200119213618581.png

python实现向量的点乘

需要注意一点,在Python中很多的数学库中将两个向量点结果还会使一个向量,结果会是每一项的相乘

import math


class Vector:
    EPSION = 1e-8  # 1/10^8,数字足够的小

    def __init__(self, my_list):
        self._values = my_list

    @classmethod
    def zero(cls, dim):
        """返回一个dim维的零向量"""
        return cls([0] * dim)

    def norm(self):
        """返回向量的模"""
        return math.sqrt(sum(e ** 2 for e in self))

    def normalize(self):
        """返回向量的单位向量"""
        if self.norm() < self.EPSION:
            raise ZeroDivisionError("向量不可以为0")
        return Vector(self._values) / self.norm()

    def __add__(self, other):
        """向量的加法,返回结果向量"""
        assert len(self) == len(other), \
            "向量的长度错误,向量之间长度必须是相等的"
        return Vector([a + b for a, b in zip(self, other)])

    def __sub__(self, other):
        """向量的减法, 返回结果向量"""
        assert len(self) == len(other), \
            "向量的长度错误,向量之间长度必须是相等的"
        return Vector([a - b for a, b in zip(self, other)])

    def dot(self, other):
        """向量的点乘,返回结果的标量"""
        assert len(self) == len(other), \
            "向量的点乘必须,向量的维度相同"
        return sum(a * b for a, b in zip(self, other))

    def __mul__(self, other):
        """返回数量乘法的结果向量, 只定义了self * other"""
        return Vector([other * e for e in self])

    def __rmul__(self, other):
        """返回向量的右乘方法, 只定义了 other * self"""
        return Vector([other * e for e in self])

    def __truediv__(self, other):
        """返回数量除法结果 self/k"""
        return (1 / other) * self

    def __pos__(self):
        """返回向量取正的结果向量"""
        return 1 * self

    def __neg__(self):
        """返回向量取负的向量结果"""
        return -1 * self

    def __iter__(self):
        """返回向量的迭代器"""
        return self._values.__iter__()

    def __getitem__(self, item):
        """取向量的第index元素"""
        return self._values[item]

    def __len__(self):
        """返回向量的长度"""
        return len(self._values)

    def __repr__(self):
        return "Vector ({})".format(self._values)

    def __str__(self):
        return "({})".format(", ".join(str(e) for e in self._values))


if __name__ == '__main__':
    vec = Vector([5, 2])
    print(vec)
    print(len(vec))

    vec2 = Vector([3, 1])
    print("{} + {} = {}".format(vec, vec2, vec + vec2))
    print("{} - {} = {}".format(vec, vec2, vec - vec2))

    print("{} * {} = {}".format(vec, 3, vec * 3))
    print("{} * {} = {}".format(3, vec, 3 * vec))

    print("+{} = {}".format(vec, +vec))
    print("-{} = {}".format(vec, -vec))

    # 创建一个二维的0向量
    zero2 = Vector.zero(2)
    print("{} + {} = {}".format(vec, zero2, vec + zero2))

    print("norm({}) = {}".format(vec, vec.norm()))
    print("norm({}) = {}".format(vec2, vec2.norm()))
    print("norm({}) = {}".format(zero2, zero2.norm()))

    print("normalize {} is {}".format(vec, vec.normalize()))
    print(vec.normalize().norm())

    print("normalize {} is {}".format(vec2, vec2.normalize()))
    print(vec2.normalize().norm())

    try:
        zero2.normalize()
    except ZeroDivisionError:
        print("0向量的单位不可求 {}.".format(zero2))

    print(vec.dot(vec2))
    
    
上一篇下一篇

猜你喜欢

热点阅读