How to Normalize a Vector in Python
To normalize a vector in Python we can either use a standard mathematical formula or use the
numpy.linalg.norm() function to complete the task for us.
Normalize a Vector Math Formula
Let's begin with an example of using the math formula to normalize a vector generated by NumPy.
import numpy as np vector = np.random.rand(5) normalised_vector = vector / np.sqrt(np.sum(vector**2)) print(normalised_vector)
[0.78077874 0.473772 0.27891699 0.09011581 0.28285882]
Note – if the array supplied is empty the above code will throw an error, so it will probably be worth putting some logic to deal with those situations unless you are absolutely sure your input data will never be empty.
Normalize a Vector with NumPy
If you don't want to deal with writing the math formula for vector normalising, use the
numpy.linalg.norm() function. Supply the original vector as the first argument and divide the result by the original vector.
import numpy as np vector = np.random.rand(5) normalised_vector = vector / np.linalg.norm(vector) print(normalised_vector)
[0.25828374 0.55423074 0.37070243 0.55211261 0.42879968]