Skip to content

Instantly share code, notes, and snippets.

@theodox
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theodox/bf5d254b5229574ef70d to your computer and use it in GitHub Desktop.
Save theodox/bf5d254b5229574ef70d to your computer and use it in GitHub Desktop.
from collections import namedtuple
import math
class Vector(object):
"""
generic vector operations
"""
def __add__(self, other):
return type(self)(*(a + b for a, b in zip(self, other)))
def __sub__(self, other):
return type(self)(*(a - b for a, b in zip(self, other)))
def __mul__(self, other):
if hasattr(other, '__iter__'):
return type(self)(*(a * b for a, b in zip(self, other)))
return type(self)(* map(lambda a: a * other, self))
def __div__(self, other):
if hasattr(other, '__iter__'):
return type(self)(*(a / b for a, b in zip(self, other)))
return type(self)(* map(lambda a: a / other, self))
def length(self):
total = sum(map(lambda a: math.pow(a, 2), self))
return math.sqrt(total)
def normalized(self):
divisor = [self.length()] * len(self)
return type(self)(*(self / divisor))
@classmethod
def add(cls, a, b):
return cls(*a) + cls(*b)
@classmethod
def sub(cls, a, b):
return cls(*a) - cls(*b)
@classmethod
def mul(cls, a, b):
return cls(*a) * cls(*b)
@classmethod
def div(cls, a, b):
return cls(*a) / cls(*b)
@classmethod
def dot(cls, left, right):
return sum(cls.mul(left, right))
@classmethod
def norm_dot(cls, left, right):
left = cls(*left).normalized()
right = cls(*right).normalized()
return sum(cls.mul(left, right))
xy = namedtuple('vect', 'x y')
xyz = namedtuple('vect', 'x y z')
xyzw = namedtuple('vect', 'x y z w')
class Vector2(Vector, xy):
pass
class Vector3(Vector, xyz):
pass
class Vector4(Vector, xyzw):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment