Best way to compute length of arbitrary dimension vector?
Chris Rebert
clp2 at rebertia.com
Mon May 30 05:24:17 EDT 2011
On Mon, May 30, 2011 at 2:11 AM, Gabriel <snoopy.67.z at googlemail.com> 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.
>
> Any ideas?
def length(self):
return sqrt(sum(coord*coord for coord in self._coords))
Cheers,
Chris
--
http://rebertia.com
More information about the Python-list
mailing list