求向量的长度也就是模

使用python来实现向量的基本运算操作
https://www.jianshu.com/p/0bd125cef1e3
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
单位向量是条件,u的模必为1

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值