Normalizing A Vector
alain at dpt-info.u-strasbg.fr
Mon Aug 2 12:19:36 CEST 2010
"Bartc" <bartc at freeuk.com> writes:
>> 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.
Sure. The above has three loops that take some time.
> 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*v+v*v+v*v))
> return (v/L,v/L,v/L)
> (Strangely, changing those divides to multiplies made it slower.)
You mean by setting L to 1.0 / math.sqrt(...) and using v*L etc.?
I think * and / have the same cost on floats, and the added / adds
some cost. But what you observe is probably caused by the overloading of
"*", that needs more type checks. You may try with operator.mul to see
if the call compensates the cost of type checking, but I doubt it.
More information about the Python-list