python中向量长度_python 中自己写方法 计算向量长度 / 实现向量归一化

本文展示了如何在Python中自定义一个向量类,包括计算向量长度和进行向量归一化的功能。通过实例演示了类的方法,如`calculateSize()`(计算向量长度)和`standardizaiton()`(向量归一化)。同时,还对代码进行了优化,增加了处理零向量归一化的异常处理。
摘要由CSDN通过智能技术生成

# coding=utf-8

import math

class Vector(object):

"""docstring for Vector"""

"""根据坐标轴列表输入 创建向量, 并创建该向量所处的空间维度"""

def __init__(self, coordinates):

super(Vector, self).__init__()

try:

if not coordinates:

raise ValueError

self.coordinates = tuple(coordinates)

self.dimension = len(coordinates)

except ValueError:

raise ValueError('The coordinates must be nonempty')

except TypeError:

raise TypeError('The coordinates must be an iterable')

# '''能够使python的内置print函数 输出向量坐标轴'''

def __str__(self):

return 'Vector: {}'.format(self.coordinates)

def __eq__(self, v):

return self.coordinates == v.coordinates

# 计算向量长度

def calculateSize(self):

result = 0

num = len(self.coordinates)

for i in range(num):

result +=self.coordinates[i] * self.coordinates[i]

result = math.sqrt(result)

return round(result,3)

# 将向量归一化

def standardizaiton(self):

size = self.calculateSize()

new_corrdinate = [round(x/size,3) for x in self.coordinates]

return Vector(new_corrdinate)

myVector = Vector([-0.221,7.437])

myVector2 = Vector([5.581,-2.136])

myVector3 = Vector([8.813,-1.331,-6.247])

myVector4 = Vector([1.996,3.108,-4.554])

print myVector.calculateSize()

print myVector2.standardizaiton()

print myVector3.calculateSize()

print myVector4.standardizaiton()

# 输出结果

# 7.44

# Vector: (0.934, -0.357)

# 10.884

# Vector: (0.34, 0.53, -0.777)

# [Finished in 0.1s]优化# 计算向量长度

def magnitude(self):

coordinates_squared = [x**2 for x in self.coordinates]

return math.sqrt(sum(coordinates_squared))

# 将向量归一化

def normalized(self):

try:

magnitude = self.magnitude()

return [x *(1./magnitude) for x in self.coordinates]

except ZeroDivisionError:

raise Exception('Cannot normalized the zero myVector2')

myVector = Vector([-0.221,7.437])

myVector2 = Vector([5.581,-2.136])

myVector3 = Vector([0,0])

print myVector.magnitude()

print myVector2.normalized()

print myVector3.normalized()

# 输出

# 7.44028292473

# [0.9339352140866403, -0.35744232526233]

# Traceback (most recent call last):

# File "/Users/Scarlett/Desktop/MovieProject/Vector.py", line 47, in # print myVector3.normalized()

# File "/Users/Scarlett/Desktop/MovieProject/Vector.py", line 38, in normalized

# raise Exception('Cannot normalized the zero myVector2')

# Exception: Cannot normalized the zero myVector2

# [Finished in 0.1s with exit code 1]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值