Normalizing A Vector

Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand
Fri Jul 30 07:46:41 EDT 2010


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.



More information about the Python-list mailing list