Normalizing A Vector
Tim Roberts
timr at probo.com
Sat Jul 31 15:45:45 EDT 2010
Lawrence D'Oliveiro <ldo at 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 dont like is having that intermediate variable L leftover after the
>computation. Heres 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, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list
mailing list