Best way to compute length of arbitrary dimension vector?

Gabriel snoopy.67.z at googlemail.com
Mon May 30 05:11:32 EDT 2011


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.

Any ideas?

Best regards,
Gabriel.



More information about the Python-list mailing list