26

Lets say I have a vector v, and I want the unit vector, i.e. v has length 1.0 Is there a direct way to get that from numpy?

I want something like:

import numpy as np
v=np.arrange(3)
v_hat = v.norm()

Rather than,

length = np.linalg.norm(v)
v_hat = v / length
CodingFrog
  • 1,225
  • 2
  • 9
  • 17

1 Answers1

36

There's no function in numpy for that. Just divide the vector by its length.

v_hat = v / (v**2).sum()**0.5

or

v_hat = v / np.linalg.norm(v)
blue_note
  • 27,712
  • 9
  • 72
  • 90