Normalizing A Vector
Terry Reedy
tjreedy at udel.edu
Sun Aug 1 19:50:10 EDT 2010
On 7/30/2010 7:46 AM, Lawrence D'Oliveiro 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.
So, instead of fooling around with error-prone, hard-to-type
constructions, just delete the damn thing!
def L
Compare those foolproof 5 chars to what at first did not work right and
even what did. And, as other said, in most real applications, you will
normalize in more than one place. In fact, you may well want a vlen
function.
def vlen(seq): return math.sqrt(sum(x*x for x in seq))
--
Terry Jan Reedy
More information about the Python-list
mailing list