Best way to compute length of arbitrary dimension vector?

Peter Otten __peter__ at web.de
Mon May 30 05:46:01 EDT 2011


Gabriel wrote:

> Well, the subject says it almost all: I'd like to write a small Vector
> class for arbitrary-dimensional vectors.
> 
> I am wondering what would be the most efficient and/or most elegant
> way to compute the length of such a Vector?
> 
> Right now, I've got
> 
>   def length(self):											# x.length() = || x ||
>     total = 0.0
>     for k in range(len(self._coords)):
>       d = self._coords[k]
>       total += d*d
>     return sqrt(total)
> 
> However, that seems a bit awkward to me (at least in Python ;-) ).
> 
> I know there is the reduce() function, but I can't seem to find a way
> to apply that to the case here (at least, not without jumping through
> too many hoops).
> 
> I have also googled a bit, but found nothing really elegant.

>>> class Vector(object):
...     def __init__(self, *coords):
...             self._coords = coords
...     def __abs__(self):
...             return math.sqrt(sum(x*x for x in self._coords))
...
>>> import math
>>> abs(Vector(1,1))
1.4142135623730951
>>> abs(Vector(3,4))
5.0





More information about the Python-list mailing list