Normalizing A Vector
Bartc
bartc at freeuk.com
Mon Aug 2 05:55:50 EDT 2010
"Alain Ketterlin" <alain at dpt-info.u-strasbg.fr> wrote in message
news:877hkdhyl5.fsf at dpt-info.u-strasbg.fr...
> 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
elements:
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.)
--
Bartc
More information about the Python-list
mailing list