Lawrence D'Oliveiro <l...@geek-central.gen.new_zealand> wrote:
>
>Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize 
>it (scale all components by the same factor) so its magnitude is 1.
>
>The usual way is something like this:
>
>    L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2])
>    V = (V[0] / L, V[1] / L, V[2] / L)
>
>What I don’t like is having that intermediate variable L leftover after the 
>computation. Here’s how to do it in one step:
>
>    V = tuple \
>      (
>              x
>          /
>              math.sqrt
>                (
>                  reduce(lambda a, b : a + b, (y * y for y in V), 0)
>                )
>          for x in V
>      )
>
>which, incidentally, also works for vectors with dimensions other than 3.

What is the matter with having a temporary variable hang around?  It's only
one double, and it far better performance than the one you posted.  As far
as I know, Python doesn't do common subexpression elimination, which means
the version you posted is doing to run the entire magnitude computation
once for every element in V.

A better solution would be to put this in a function:

  def Normalize(V):
      L = math.sqrt( sum(a*a for a in V) )
      return (a/L for a in V)

Now the temporary goes away at the end of the function.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to