Normalizing A Vector

Alain Ketterlin alain at
Mon Aug 2 12:19:36 CEST 2010

"Bartc" <bartc at> 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[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.)

You mean by setting L to 1.0 / math.sqrt(...) and using v[0]*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.

-- Alain.

More information about the Python-list mailing list