Wednesday, 21 August 2013

User-defined Vector class for python

User-defined Vector class for python

I've been looking for a way to deal with vectors in python and havent
found a solution here or in the documentation that completely fits me.
This is what I've come up with so far for a vector class:
class vec(tuple):
def __add__(self, y):
if len(self)!=len(y):
raise TypeError
else:
ret=[]
for i,entry in enumerate(self):
ret.append(entry+y[i])
return vec(ret)
def __mul__(self, y):
t=y.__class__
if t == int or t==float:
#scalar multiplication
ret=[]
for entry in self:
ret.append(y*entry)
return vec(ret)
elif t== list or t==tuple or t==vec:
# dot product
if len(y)!=len(self):
print 'vecs dimensions dont fit'
raise TypeError
else:
ret=0
for i,entry in enumerate(self):
ret+=entry*y[i]
return ret
Theres a little bit more, left out to keep things short. So far
everythings working fine but I have lots of tiny specific questions (and
will probably post more as they come up):
Are there base classes for the numeric and sequence-types and how can I
address them?
How can I make all of this more Python-y? I want to learn how to write
good Python code, so if you find something that's inefficient or just
ugly, please tell me.
What about precision? As python seems to cast from integers to floats only
if necessary, input and output are usually of the same type. So there
might be problems with very large or small numbers, but I don't really
need those currently. Should I generally worry about precision or does
python do that for me? Would it be better to convert to the largest
possible type automatically? Which one is that? What happens beyond that?
I want to use n-dimensional vectors in a project involving lots of
vectorial equations and functions and I'd like to be able to use the usual
notation that's used in math textbooks. As you can see this inherits from
tuple (for easy construction, immutability and indexing) and most built in
functions are overwritten in order to use the (+,-,*,..)- operators. They
only work if the left operand is a vec (can I change that?).
Multiplication includes dot- and scalar product, pow is also used for the
cross-product if both vecs are 3D.

No comments:

Post a Comment