各位大神好!
我在学习的一个线代基础课中,需要用到Python来计算向量,其中有一段代码是这样的:
from math import sqrt, acos, pi #导入sqrt, acos, pi
from decimal import Decimal, getcontext
getcontext().prec = 30
class Vector():
CANNOT_NORMALIZE_ZERO_VECTOR_MSG = 'Cannot normalize the zero vector'
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple([Decimal(x) for x in coordinates])
self.dimension = len(self.coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def plus(self, v):
"""向量加法"""
new_coordinates = [x + y for x, y in zip(self.coordinates, v.coordinates)]
return Vecto