使用python來實現向量的基本運算操作

向量的長度

  • 向量的長度又叫向量的模,使用雙豎線來包裹向量表示向量的長度
  • 下面是二維向量中取模的算法,使用勾股定理即可
image-20200117213429377.png
  • 下面是三維向量中取模的方式(求和的方式)
image-20200117213908453.png
  • n維向量的同理
image-20200117215318089.png

單位向量

  • 單位向量有無數個
  • 二維空間中,有兩個特殊的單位向量 \vec{e}=(1,0) \vec{e}=(0,1)
  • 三維空間中,有三個特殊的單位向量 \vec{e}=(1,0,0) \vec{e}=(0,0,1) \vec{e}=(0,1,0)
  • n維空間中,有n個特殊的單位向量 \vec{e}=(1,0,...,0) \vec{e}=(0,0,...,1) \vec{e}=(0,1,...,0)
image-20200117215614012.png

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 __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))

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容