Best way to compute length of arbitrary dimension vector?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon May 30 15:01:08 EDT 2011


En Mon, 30 May 2011 06:46:01 -0300, Peter Otten <__peter__ at 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




More information about the Python-list mailing list