2

Is there a built-in method for normalising an n-vector ( i.e. evaluating the unit vector v_{hat} = v/||v|| for an n-dimensional vector) in Python or in either of the major Python numerical libraries numpy or scipy?

I've written a method using norm from the numpy linear algebra module (numpy.linalg):

def normaliseVector(nVector):
    return nVector/numpy.linalg.norm(nVector)

which seems to work fine. I tested it with the following input:

normaliseVector([3, 4, 5])

which returns the correct answer for this case. It just struck me that there might be a method out there for doing this already, or if not that it might be a useful thing to have a well-tested method for this.

santosh
  • 21
  • 3
  • 1
    As the marked duplicate specifically deals with scikit-learn: Yes, dividing by `np.linalg.norm` is the canonical way to do this in numpy. There's no built in function for it. However, if you'd prefer to do the operation in-place (faster, saves memory, but modifies the input), you can do `vector /= np.linalg.norm(vector)`. Don't use `/=` unless you are aware of datatype issues (it will produce an array of zeros with any integer datatype) and in-place modification, though! – Joe Kington Jun 10 '15 at 17:19

0 Answers0