Normalizing A Vector

Bartc bartc at
Mon Aug 2 11:55:50 CEST 2010

"Alain Ketterlin" <alain at> wrote in message 
news:877hkdhyl5.fsf at
> Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> writes:
>> 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)

> Your best bet is to define a function that does the normalization. Your
> (local) name will disappear at the end of the call. If you want it to
> work for any vector size:
> def norm(V):
>    L = math.sqrt( sum( [x**2 for x in V] ) )
>    return [ x/L for x in V ]

There's a cost involved in using those fancy constructions. I found the 
following to be about twice as fast, when vectors are known to have 3 

def norm3d(v):
    L = math.sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2]))
    return (v[0]/L,v[1]/L,v[2]/L)

(Strangely, changing those divides to multiplies made it slower.)


More information about the Python-list mailing list