def unitvec(vec):
if scipy.sparse.issparse(vec): <EOL><INDENT>vec = vec.tocsr()<EOL>veclen = numpy.sqrt(numpy.sum(vec.data ** <NUM_LIT:2>))<EOL>if veclen > <NUM_LIT:0.0>:<EOL><INDENT>return vec / veclen<EOL><DEDENT>else:<EOL><INDENT>return vec<EOL><DEDENT><DEDENT>if isinstance(vec, numpy.ndarray):<EOL><INDENT>vec = numpy.asarray(vec, dtype=float)<EOL>veclen = numpy.linalg.norm(vec)<EOL>if veclen > <NUM_LIT:0.0>:<EOL><INDENT>return vec / veclen<EOL><DEDENT>else:<EOL><INDENT>return vec<EOL><DEDENT><DEDENT>
Scale a vector to unit length. The only exception is the zero vector, which
is returned back unchanged.