Best way to compute length of arbitrary dimension vector?

Ian Kelly ian.g.kelly at gmail.com
Fri Jun 3 18:17:53 EDT 2011


On Fri, Jun 3, 2011 at 3:53 PM, Gabriel <snoopy.67.z at googlemail.com> wrote:
> But still, is this solution really faster or better than the one using
> list comprehension and the expression 'x*x'?

No, not really.

>c:\python32\python -m timeit -s "coords = list(range(100))" -s "from math import hypot" -s "from functools import reduce" "reduce(hypot, coords, 0)"
10000 loops, best of 3: 53.2 usec per loop

>c:\python32\python -m timeit -s "coords = list(range(100))" -s "from math import sqrt, fsum" "sqrt(fsum(x*x for x in coords))"
10000 loops, best of 3: 32 usec per loop

>c:\python32\python -m timeit -s "coords = list(range(100))" -s "from math import sqrt" "sqrt(sum(x*x for x in coords))"
100000 loops, best of 3: 14.4 usec per loop



More information about the Python-list mailing list