Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #6647
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: Best way to compute length of arbitrary dimension vector? |
| Date | 2011-05-30 11:46 +0200 |
| Organization | None |
| References | <43d7a46e-3f48-4c11-a66b-a47a3d6b9b9d@k16g2000yqm.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2258.1306749013.9059.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Best way to compute length of arbitrary dimension vector? Gabriel <snoopy.67.z@googlemail.com> - 2011-05-30 02:11 -0700
Re: Best way to compute length of arbitrary dimension vector? Chris Rebert <clp2@rebertia.com> - 2011-05-30 02:24 -0700
Re: Best way to compute length of arbitrary dimension vector? Peter Otten <__peter__@web.de> - 2011-05-30 11:46 +0200
Re: Best way to compute length of arbitrary dimension vector? Gabriel <snoopy.67.z@googlemail.com> - 2011-05-30 06:38 -0700
Re: Best way to compute length of arbitrary dimension vector? Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-02 17:19 -0600
Re: Best way to compute length of arbitrary dimension vector? Gabriel <snoopy.67.z@googlemail.com> - 2011-06-03 14:53 -0700
Re: Best way to compute length of arbitrary dimension vector? Ian Kelly <ian.g.kelly@gmail.com> - 2011-06-03 16:17 -0600
Re: Best way to compute length of arbitrary dimension vector? Robert Kern <robert.kern@gmail.com> - 2011-06-03 18:12 -0500
Re: Best way to compute length of arbitrary dimension vector? "Gabriel Genellina" <gagsl-py2@yahoo.com.ar> - 2011-05-30 16:01 -0300
Re: Best way to compute length of arbitrary dimension vector? Gabriel <snoopy.67.z@googlemail.com> - 2011-06-01 12:35 -0700
csiph-web