各位大神好!
我在学习的一个线代基础课中,需要用到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 Vector(new_coordinates)
def dot(self, v):
"""计算向量点积"""
return sum([x * y for x, y in zip(self.coordinates, v.coordinates)])
def angle_with(self, v, in_degrees = False):
"""计算向量夹角"""
try:
u1 = self.normalized()
u2 = v.normalized()
angle_in_radians = acos(u1.dot(u2))
if in_degrees:
degrees_per_radian = 180. / pi
return angle_in_radians * degrees_per_radian
else:
return angle_in_radians
except Exception as e:
if str(e) == self.CANNOT_NORMALIZE_ZERO_VECTOR_MSG:
raise Exception('Cannot compute an angle with the zero vector')
else:
raise e
print('\n向量加法')
v = Vector([8.218, -9.341])
w = Vector([-1.129, 2.111])
print(v.plus(w))
print('\n计算向量夹角')
v = Vector(['3.183', '-7.627'])
w = Vector(['-2.668', '5.319'])
print(v.angle_with(w))
v = Vector(['7.35', '0.221', '5.188'])
w = Vector(['2.751', '8.259', '3.985'])
print(v.angle_with(w, in_degrees=True))
在向量加法的代码中,这个 self.coordinates
是 v = Vector([8.218, -9.341])
传入的值,v.coordinates
是 w = Vector([-1.129, 2.111])
传入的值,我有个问题就是,为什么 v
后面要加上coordinates
呢?这个 v
是类似 self
那样作为引用,用于访问这个属性 coordinates
吗?为什么不可以直接使用 v
呢?
另外在“计算夹角向量”的代码中:
angle_in_radians = acos(u1.dot(u2))
中的 (u1.dot(u2))
该怎么理解好呢?
请大神赐教,谢谢!
v是代表一个对象,你打印v会获取它的内存地址,coordinates 是v的一个属性,你打印v.coordinates 可以获取属性里面的值。当然你也直接用v,这样你需要重写v的魔方方法,也就是__repr__方法,但是返回值需要转换成str类型,否则会报类型错误~