實現高效的Vector / Point類的最佳方法是什么(甚至更好:是否有一個),可以在
Python 2.7和3.x中使用?
我找到了the blender-mathutils,但它們似乎只支持Python 3.x.然后是this Vector class,使用numpy,但它只是一個3D矢量.使用具有靜態屬性(x和y)的像kivy’s vector class(sourcecode)的Vector的列表似乎也很奇怪. (有所有這些列表方法.)
目前我正在使用一個擴展了namedtuple的類(如下所示),但這樣做的缺點是無法更改坐標.我認為當成千上萬的對象移動并且每次都創建一個新的(矢量)元組時,這可能會成為一個性能問題. (對?)
class Vector2D(namedtuple('Vector2D', ('x', 'y'))):
__slots__ = ()
def __abs__(self):
return type(self)(abs(self.x), abs(self.y))
def __int__(self):
return type(self)(int(self.x), int(self.y))
def __add__(self, other):
return type(self)(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return type(self)(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return type(self)(self.x * other, self.y * other)
def __div__(self, other):
return type(self)(self.x / other, self.y / other)
def dot_product(self, other):
return self.x * other.x + self.y * other.y
def distance_to(self, other):
""" uses the Euclidean norm to calculate the distance """
return hypot((self.x - other.x), (self.y - other.y))
編輯:我做了一些測試,似乎使用numpy.array或numpy.ndarray作為矢量太慢了. (例如,獲取一個項目需要幾乎兩倍的時間,更不用說創建一個數組.我認為它更適合于對大量項目進行計算.)
所以,我正在尋找一個輕量級的矢量類,它具有固定數量的字段(在我的例子中只有x和y),可以用于游戲. (如果已經有一個經過充分測試的車輪,我不想重新發明輪子.)