Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #6669
| From | "Gabriel Genellina" <gagsl-py2@yahoo.com.ar> |
|---|---|
| Subject | Re: Best way to compute length of arbitrary dimension vector? |
| Date | 2011-05-30 16:01 -0300 |
| References | <43d7a46e-3f48-4c11-a66b-a47a3d6b9b9d@k16g2000yqm.googlegroups.com> <irvp0e$mc6$2@dough.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2278.1306781932.9059.python-list@python.org> (permalink) |
En Mon, 30 May 2011 06:46:01 -0300, Peter Otten <__peter__@web.de> escribió: > Gabriel wrote: > >> Well, the subject says it almost all: I'd like to write a small Vector >> class for arbitrary-dimensional vectors. >> > >>>> 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 Using math.fsum instead of sum may improve accuracy, specially when len(coords)≫2 py> import math py> py> def f1(*args): ... return math.sqrt(sum(x*x for x in args)) ... py> def f2(*args): ... return math.sqrt(math.fsum(x*x for x in args)) ... py> pi=math.pi py> args=[pi]*16 py> abs(f1(*args)/4 - pi) 4.4408920985006262e-16 py> abs(f2(*args)/4 - pi) 0.0 -- Gabriel Genellina
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